From: Brian Candler Date: 2008-11-20T01:13:02+09:00 Subject: Re: build hash by iterating > And if I want to change each hash value from fixnum to string, how would > that be done? > > this is not working: new_hash = h.each_key {|k| h[k].to_s} The simple two-liner is this: new_hash = {} h.each { |k,v| new_hash[k] = v.to_s } The one-liner uses 'inject': new_hash = h.inject({}) { |n,(k,v)| n[k] = v.to_s; n } To understand 'inject', note that: 1. you pass in the new object for accumulating the result ({}) 2. for each call of the block, the accumulator is passed as the first argument (n) 3. the return value of the block is used as the new accumulator (for the next iteration, or as the final result). In this case, we wish to continue using n, so we return that as the value of the block. -- Posted via http://www.ruby-forum.com/.