Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hash[] vs to_h, are they the same, and if so which is better?

Tags:

ruby

hash

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"}
like image 427
kleaver Avatar asked Feb 03 '15 15:02

kleaver


People also ask

What does Hash do in Ruby?

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.

What is new Hash Ruby?

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.

How do I get the Hash value in Ruby?

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.


1 Answers

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.

like image 106
sawa Avatar answered Oct 24 '22 22:10

sawa