> Hash[:a,2,:b,4]
=> {:a=>2, :b=>4}
> Hash[:a,1]
=> {:a=>1}
> Hash[[:a,1]]
=> {}
> Hash[[[:a,1]]]
=> {:a=>1}
views:
60answers:
1
+8
A:
You can pass the key-value pairs two ways:
- Directly as arguments to
Hash::[]
, with the keys and values alternating - 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
2010-09-17 00:30:41
Yeah, check out `Hash[[:a,1],1]` for more interestingness.
BaroqueBobcat
2010-09-17 00:32:24
Or `Hash[[[0],[]]]`.
Mark Byers
2010-09-17 00:34:14
`Hash[[[0],[]]]` is equivalent to `Hash[[[0]]]`. The missing second element in the pair defaults to `false`.
Chuck
2010-09-17 00:38:04