David Vallner
10/29/2006 1:13:00 PM
Robert Klemme wrote:
> Logan Capaldo wrote:
>> Alternative decandence:
>>
>> class Array
>> def to_hsh
>> require 'enumerator'
>> to_enum(:each_slice, 2).to_a.inject({}) { |h, (k, v)|
>> h.update(k=>v) }
>> end
>> end
>
> This seems a bit inefficient. If you write a method then I'd prefer
>
> require 'enumerator'
> module Enumerable
> def to_hash
> h = {}
> to_enum(:each_slice, 2).each {|k,v| h[k]=v}
> h
> end
> end
>
> irb(main):021:0> %w( a b c d ).to_hash
> => {"a"=>"b", "c"=>"d"}
> irb(main):022:0> (1..10).to_hash
> => {5=>6, 1=>2, 7=>8, 3=>4, 9=>10}
>
Well, if Ruby had clean blocks, the method using #inject might be more
efficient - I don't know how expensive the implicit hash construction
for method parameters is. Smalltalk muscle memory working there?
David Vallner