I have two arrays
a = [:foo, :bar, :baz, :bof]
and
b = ["hello", "world", 1, 2]
I want
{:foo => "hello", :bar => "world", :baz => 1, :bof => 2}
Any way to do this?
The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.
Arrays can be equal if they have the same number of elements and if each element is equal to the corresponding element in the array. To compare arrays in order to find if they are equal or not, we have to use the == operator.
In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.
Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key.
h = Hash[a.zip b] # => {:baz=>1, :bof=>2, :bar=>"world", :foo=>"hello"}
...damn, I love Ruby.
Just wanted to point out that there's a slightly cleaner way of doing this:
h = a.zip(b).to_h # => {:foo=>"hello", :bar=>"world", :baz=>1, :bof=>2}
Have to agree on the "I love Ruby" part though!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With