From: Stefan Rusterholz Date: 2008-01-11T01:54:08+09:00 Subject: Re: About array to hash conversion Holden Holden wrote: > yermej wrote: >> On Jan 9, 3:31�pm, Holden Holden wrote: >>> >>> return)? >> These would only work in one specific case. What would this do? >> >> [1, 2, 3].to_h > > That's why I prefer [key, value] pairs, to avoid any ambiguity. > > However, a theorical [1,2,3].to_h should give the same error than > Hash[*array] gives: > > irb(main):002:0> Hash[*[1,2,3]] > ArgumentError: odd number of arguments for Hash I disagree. Array#to_hash should work so that hash.to_a.to_hash == hash, in other words it should create a hash only if it contains key value tuples. > array.inject({}) {|ha, (k, v)| ha[k] = v; ha} There's absolutely no advantage using inject like this. h={}; array.each { |k,v| h[k]=v } Is less code and faster. > ar.to_enum(:each_with_index).inject({}) {|h, (v,k)| h[k]=v;h} Same here h={}; array.each_with_index { |k,v| h[k]=v } Personally I use the following code in my lib: # create a hash from an array with keys and an array with values # you can set default or provide a block just as with Hash::new def Hash.zip(keys, values, default=nil, &block) hash = block_given? ? Hash.new(&block) : Hash.new(default) keys.zip(values) { |k,v| hash[k]=v } hash end class Array # create a hash from an array of [key,value] tuples # you can set default or provide a block just as with Hash::new # Note: if you use [key, value1, value2, value#], hash[key] will # be [value1, value2, value#] def to_hash(default=nil, &block) hash = block_given? ? Hash.new(&block) : Hash.new(default) each { |(key, *value)| hash[key]=*value } hash end end Regards Stefan -- Posted via http://www.ruby-forum.com/.