From: Robert Klemme Date: 2006-10-30T06:45:12+09:00 Subject: Re: Define a hash using %q? David Vallner wrote: > 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? I am not sure what you are at here. Object creation always costs - even small hashes. Reason is memory allocation and GC management overhead. Regards robert