Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following string and I would like to convert it to a hash printing the below result

string = "Cow, Bill, Phone, Flour"

hash = string.split(",")

>> {:animal => "Cow", :person: "Bill", :gadget => "Phone", 
    :grocery => "Flour"}
share|improve this question

2 Answers 2

up vote 1 down vote accepted
hash = Hash[[:animal, :person, :gadget, :grocery].zip(string.split(/,\s*/))]
share|improve this answer
    
Thanks for your answer Max but that actually prints {:animal=>"Cow, Bill, Phone, Flour", :person=>nil, :gadget=>nil, :grocery=>nil} –  fiyah Jun 25 at 20:30
    
Judging by the edit of your comment, I don't think you actually looked at what my code was doing. My code definitely worked (I tested it before posting the answer) but I've updated it to split more generically as well. –  Max Jun 25 at 20:35
    
my apologies...I had an extra variable in my string –  fiyah Jun 25 at 20:42

The answer by @Max is quite nice. You might understand it better as:

def string_to_hash(str)
  values = str.split(/,\s*/)
  names = [:animal, :person, :gadget, :grocery]
  Hash[names.zip(values)]
end

Here is a less sophisticated approach:

def string_to_hash(str)
  parts = str.split(/,\s*/)
  Hash[
    :animal  => parts[0],
    :person  => parts[1],
    :gadget  => parts[2],
    :grocery => parts[3],
  ]
end
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.