These appear to be identical. Is there a preference, performance differences, etc?
Hash[[[:a, 'foo'], [:b, 'bar']]]
#=> {:a=>"foo", :b=>"bar"}
[[:a, 'foo'], [:b, 'bar']].to_h
#=> {:a=>"foo", :b=>"bar"}
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.
In Ruby, Hash is a collection of unique keys and their values. Hash is like an Array, except the indexing is done with the help of arbitrary keys of any object type. In Hash, the order of returning keys and their value by various iterators is arbitrary and will generally not be in the insertion order.
In Ruby, the values in a hash can be accessed using bracket notation. After the hash name, type the key in square brackets in order to access the value.
They are not the same. Both can take an array of arrays:
Hash[[[1, 2], [3, 4]]] #=> {1=>2, 3=>4}
[[1, 2], [3, 4]].to_h #=> {1=>2, 3=>4}
but in addition to that, Hash.[]
has more quirky syntax. It can accept elements directly:
Hash[1, 2, 3, 4] #=> {1=>2, 3=>4}
If you try something in between, you will get unexpected results:
Hash[[1, 2], [3, 4]] #=> {[1, 2]=>[3, 4]}
And although giving it odd numbers of elements usually returns an error, which will help you in debugging:
Hash[1, 2, 3]
#=> ArgumentError: odd number of arguments for Hash
with certain kind of elements, it will silently return an empty hash (but with a warning), which will be hard to debug:
Hash[[1, 2]]
#=> {}
#=> warning: wrong element type Fixnum at 0 (expected array)
For this reason, Hash.[]
is tricky. Since Array#to_h
has been introduced, there is no reason to use Hash.[]
. Array#to_h
is better. The Ruby developers will not remove Hash.[]
just for compatibility.
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