Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby, why is Hash[:a, 1] and Hash[[[:a, 1]]] giving the same result {:a => 1}, while Hash[[:a,1]] gives an empty hash?

Tags:

ruby

hash

 > Hash[:a,2,:b,4]
 => {:a=>2, :b=>4} 

 > Hash[:a,1]
 => {:a=>1} 

 > Hash[[:a,1]]
 => {} 

 > Hash[[[:a,1]]]
 => {:a=>1}
like image 375
nonopolarity Avatar asked Feb 26 '23 05:02

nonopolarity


1 Answers

You can pass the key-value pairs two ways:

  1. Directly as arguments to Hash::[], with the keys and values alternating
  2. As an array of pairs, each represented by an array containing a key and a value

The first form fits 1, the second form fits 1, the fourth form fits 2, but the third form doesn't fit either (it consists of a single array, but neither :a nor 1 is a key-value pair).

The reason the second form is useful is because that's what you tend to get from Hash's Enumerable methods — an array of key-value pairs in arrays. So you can write Hash[some_hash.map {|k, v| [k, v+1]}] and you'll end up with a Hash transformed the way you want.

like image 188
Chuck Avatar answered May 05 '23 14:05

Chuck