tags:

views:

60

answers:

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

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

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

 > Hash[[[:a,1]]]
 => {:a=>1}
+8  A: 

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.

Chuck
Yeah, check out `Hash[[:a,1],1]` for more interestingness.
BaroqueBobcat
Or `Hash[[[0],[]]]`.
Mark Byers
`Hash[[[0],[]]]` is equivalent to `Hash[[[0]]]`. The missing second element in the pair defaults to `false`.
Chuck