2006/6/22, Ashley M. [email protected]:
On Jun 22, 2006, at 8:25 pm, Simen E. wrote:
Hash[*self.map{|m|m.send(method).to_s.to_sym}.zip(self).flatten ]
Disclaimer: inject is probably more appropriate, but my solution at
least looks cooler 
Simen… you don’t come from a Perl background do you 
LOL - Could also be awk - because the code looks so awkward. :-))
On Jun 22, 2006, at 8:09 pm, Simon Kröger wrote:
class Array
def hash_on(method)
inject({}){|h, i| h.merge({i.send(method).to_s.to_sym, i})}
end
end
I like!
I like Robin’s inject solution more - it’s more efficient and avoids
all those short lived hash objects. Also, I’d put it into Enumerable,
add a block and provide a list of args instead of the method name
only:
module Enumerable
def to_hash(*args,&b)
inject({}) {|h,e| h[b ? b[e] : e.send(*args)] = e; h}
end
end
irb(main):019:0> %w{foo bar baz}.to_hash {|x| x[0]}
=> {102=>“foo”, 98=>“baz”}
irb(main):020:0> %w{foo bar baz}.to_hash(:[], 0)
=> {102=>“foo”, 98=>“baz”}
silly example to demonstrate what you cannot do without a block
irb(main):022:0> %w{foo bar baz}.to_hash {|x| x.length * rand(100)}
=> {132=>“bar”, 15=>“foo”, 186=>“baz”}
Incidentally… what is the convention here on CCing posters in
replies? I come from the FreeBSD lists where it’s normal to CC the
poster so they don’t have to check the list. But people on Ruby
lists are really surprised when I do that.
I usually don’t because I assume people are checking thelist anyway -
and until now nobody has complaint that he / she missed a posting from
me. 
Kind regards
robert