Ezra Zygmuntowicz
1/26/2006 11:11:00 PM
On Jan 26, 2006, at 2:55 PM, Jon Baer wrote:
> Nice .. well that works :-) but in the constructor can you tell me
> what "*" would literally "mean"?
>
> Does this just take only an Array obj or could you place any object
> in there w/ public attributes/methods?
>
> (Was this covered in pick-axe somewhere I missed?)
>
> Thank you, much appreciated ...
>
> - Jon
>
> On Jan 26, 2006, at 3:06 PM, James Edward Gray II wrote:
>
>> >> h1 = {"foo1"=>"bar1", "foo2"=>"bar2"}
>> => {"foo1"=>"bar1", "foo2"=>"bar2"}
>> >> h2 = Hash[*h1.select { |k, v| v == "bar2" }.flatten]
>
>
The "*" is sometimes called the "splat" operator. If you use the Hash
[] constructor and pass in an array with the * before it it will turn
the array into a hash using pairs of the array members to create the
key => values of the hash. Maybe a littel more code tells it best:
ezra:~/up root# irb
irb(main):001:0> a = [1,2,3,4,5,6,7,8]
=> [1, 2, 3, 4, 5, 6, 7, 8]
irb(main):002:0> b = Hash[*a]
=> {5=>6, 1=>2, 7=>8, 3=>4}
irb(main):003:0> h1 = {"foo1"=>"bar1", "foo2"=>"bar2"}
=> {"foo1"=>"bar1", "foo2"=>"bar2"}
irb(main):004:0> h1.select { |k, v| v == "bar2" }.flatten
=> ["foo2", "bar2"]
irb(main):005:0> h2 = Hash[*h1.select { |k, v| v == "bar2" }.flatten]
=> {"foo2"=>"bar2"}
irb(main):006:0>
Cheers-
-Ezra