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}
  • June 8, 2005
  • Dealing with ruby

There are 4 comments

  1. 13 days later, amchi said...

    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?

  2. 13 days later, Ryan said...

    Ha, that was fun. Use Enumerable#zip, and then Array.toh (http://www.fivesevensix.com/articles/2005/06/08/array-toh-redux)

    
    keys = [:a, :b, :c]
    values = [1, 2, 3]
    keys.zip values
    => [[:a, 1], [:b, 2], [:c, 3]]
    keys.zip(values).to_h do |h,(key,value)|
      h[key] = value
    end
    => {:a=>1, :b=>2, :c=>3}
    
  3. 13 days later, amchi said...

    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.

  4. 100 days later, Troy said...

    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}