Convert nested array to hash in Ruby
Let’s say you have a complex data structure containing nested arrays like this:
arr = [
[:id, 233],
[:name, "ruby tuesday"],
[:email, "ruby@tuesday.com"]
]
And you want to convert it to a hash where the keys of the hash are the first element of each subarray and the keys value is the second item in the subarray. you can accomplish using the Hash
classes class method []
, like so:
Hash[arr]
=> {:id=>233, :name=>"ruby tuesday", :email=>"ruby@tuesday.com"}
Looking for more red jewel programming insights? Why not head over to Ruby [0..-2] explained