Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/hash_extensions.rb

Instance Method Summary collapse

Instance Method Details

#map_keys(&block) ⇒ Object Also known as: rekey, revalue

Call a block for every key in the Hash, and replace each key with the block’s return value. This returns a new Hash, so you do not need to call #rehash on it.



4
5
6
7
8
# File 'lib/hash_extensions.rb', line 4

def map_keys(&block)
  mapped = Hash.new
  self.to_a.map{|k,v| [yield(k), v] }.each{|k,v| mapped[k] = v}
  mapped
end

#map_pairs(&block) ⇒ Object

Call a block for every (key, value) pair in the hash, passing them in as a 2-element Array. The block should return a similar 2-element array of (key, value) which will be used to replace the original key and value.



22
23
24
25
26
# File 'lib/hash_extensions.rb', line 22

def map_pairs(&block)
  mapped = Hash.new
  self.to_a.map{|k,v| yield(k,v) }.each{|k,v| mapped[k] = v}
  mapped
end

#map_values(&block) ⇒ Object

Call a block for every value in the Hash, and replace each value with the block’s return value.



12
13
14
15
16
# File 'lib/hash_extensions.rb', line 12

def map_values(&block)
  mapped = Hash.new
  self.to_a.map{|k,v| [k, yield(v)] }.each{|k,v| mapped[k] = v}
  mapped
end