From: Simen Edvardsen Date: 2006-06-23T04:25:57+09:00 Subject: Re: Turning an Array into a Hash based on an attribute value Disclaimer: inject is probably more appropriate, but my solution at least looks cooler ;) On 6/22/06, Simen Edvardsen wrote: > $ irb > irb(main):001:0> class Array > irb(main):002:1> def hash_on(method) > irb(main):003:2> > Hash[*self.map{|m|m.send(method).to_s.to_sym}.zip(self).flatten ] > irb(main):004:2> end > irb(main):005:1> end > => nil > irb(main):006:0> [1, "2", :three].hash_on(:class) > => {:String=>"2", :Symbol=>:three, :Fixnum=>1} > irb(main):007:0> > > > On 6/22/06, Ashley Moran wrote: > > A guy I work with has some some work on an ActiveRecord class that > > basically reads static lookup data, and contains (among other things) > > an "identifier" attribute. Given an array of all these objects he > > wanted to access them by the contents of the identifier attribute, eg: > > > > data_items = DataItem.find(:all) > > # data_items[3].identifier => "my_identifier" > > data_items[:my_identifier].do_something # => data_items[3].do_something > > > > The best I can come up with is this: > > > > class Array > > def hash_on(method) > > method = method.to_sym > > hash = { } > > self.each do |i| > > hash[i.send(method).to_s.to_sym] = i > > end > > hash > > end > > end > > > > > [1, "2", :three].hash_on(:class) > > => {:String=>"2", :Symbol=>:three, :Fixnum=>1} > > > > Is there a neater (one-line?) way I missed? > > > > Ashley > > > > > > > -- > - Simen > > -- - Simen