Reputation: 147
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"}
Upvotes: 0
Views: 54
Reputation: 156682
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
Upvotes: 0
Reputation: 22385
hash = Hash[[:animal, :person, :gadget, :grocery].zip(string.split(/,\s*/))]
Upvotes: 1