Here’s another “what’s the most elegant way to do X in Ruby” type of questions. Consider the response from a webservice with key:value pairs on each line of the return body, along the lines of
key1:val1
key2:val2
key3:val3
I want to create a Ruby hash with this data, {"key1" => "val1", ...}. Algorithmically I can git ‘er done with
hash = {}
body.lines.each do |line|
key, val = line.split(':')
hash[key] = val
end
but I’m guessing there’s a one-liner or two-liner that is even more elegant.
Here is my suggestion:
Explanation
Hash[object]creates a new hash from the object. Where the object is one of: