Hash#remap
Since we're mapping Array's around, we might as well do Hash's too. (And yes, I actually needed these)
class Hash # remap the keys and/or values of a hash to a new hash def remap(hash={}) each { |k,v| yield hash, k, v } hash end # remap the keys and/or values of a hash to self. Probably wouldn't # do the keys unless providing aliases. def remap!(&block) remap self, &block end end
I just know you had to do this recently:
stuff = {"a"=>5, "b"=>10, "c"=>15} stuff.remap do |h, k, v| h[(k * 2).to_sym] = v * 2 end => {:aa=>10, :bb=>20, :cc=>30}
There are 4 comments
I got a question here. I have two arrays - one is a key array and the other is a value array. How do I map it into a hash - easily?
Ha, that was fun. Use
Enumerable#zip, and thenArray.toh(http://www.fivesevensix.com/articles/2005/06/08/array-toh-redux)Thanks Ryan for the quick solution. I'm unlearning php and started Ruby last week. It's taking some time so still comprehending your Array#to_h. Anyway thanks for the cool site, it is informative.
This is the solution that you've been looking for all along for array.to_h Hash[*keys.zip(values)] => {:b=>2, :a=>1, :c=>3}