0

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"}

2 Answers 2

1
hash = Hash[[:animal, :person, :gadget, :grocery].zip(string.split(/,\s*/))]
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer Max but that actually prints {:animal=>"Cow, Bill, Phone, Flour", :person=>nil, :gadget=>nil, :grocery=>nil}
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.
my apologies...I had an extra variable in my string
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.