Robert Klemme
10/9/2008 7:31:00 AM
2008/10/9 William James <w_a_x_man@yahoo.com>:
> On Oct 8, 8:00 pm, Pete Hodgson <phodg...@lyris.com> wrote:
>> Given:
>>
>> Person = Struct.new(:name,:age,:city)
>> people_array = [
>> Person.new('bob',12,'SFO'),
>> Person.new('dave',14,'NYC'),
>> Person.new('jane',6,'LDN') ]
>>
>> Is there a cleaner way to build people_map? I'm thinking there might be
>> something like:
> Hash[ * people_array.map{|x| [ x.name, x ] }.flatten ]
> ==>{"dave" => #<struct Person name="dave", age=14, city="NYC">,
> "jane" => #<struct Person name="jane", age=6, city="LDN">,
> "bob" => #<struct Person name="bob", age=12, city="SFO">}
And since we did not have an inject version so far:
irb(main):001:0> require 'pp'
=> true
irb(main):002:0> Person = Struct.new(:name,:age,:city)
=> Person
irb(main):003:0> people_array = [
irb(main):004:1* Person.new('bob',12,'SFO'),
irb(main):005:1* Person.new('dave',14,'NYC'),
irb(main):006:1* Person.new('jane',6,'LDN'),
irb(main):007:1* ]
=> [#<struct Person name="bob", age=12, city="SFO">, #<struct Person
name="dave", age=14, city="NYC">, #<struct Person name="jane", age=6,
city="LDN">]
irb(main):008:0> pp( people_map = people_array.inject({}) do |ha,pe|
irb(main):009:2* ha[pe.name] = pe
irb(main):010:2> ha
irb(main):011:2> end )
{"dave"=>#<struct Person name="dave", age=14, city="NYC">,
"jane"=>#<struct Person name="jane", age=6, city="LDN">,
"bob"=>#<struct Person name="bob", age=12, city="SFO">}
=> nil
Just for completeness reasons of course. ;-)
Kind regards
robert
--
remember.guy do |as, often| as.you_can - without end