Class: Hash

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

Instance Method Summary collapse

Instance Method Details

#map_pairs(&block) ⇒ Object

Returns a new hash which is a copy of the current hash but each key-value pair is replaced by the result of running it through block.

If block returns duplicate keys, they will be overwritten in the resulting hash.

{'a'=>1, 'b'=>2}.map_pairs { |k,v| [k*2, v+1] } #=> {'aa'=>2, 'bb'=>3}
{'a'=>1, 'b'=>2}.map_pairs { ["cat","dog"] }   #=> {'cat'=>'dog'}

If no block is given, an Enumerator is returned instead.



94
95
96
97
98
99
100
101
102
# File 'lib/hashmap.rb', line 94

def map_pairs &block # :yields: key, value
  return enum_for(:map_pairs) unless block_given?
  hsh = {}
  each do |k, v|
    a, b = yield k, v
    hsh[a] = b
  end
  hsh
end

#map_pairs!(&block) ⇒ Object

Replaces the values in hsh by running them each through block.

See: #map_pairs



109
110
111
112
# File 'lib/hashmap.rb', line 109

def map_pairs! &block # :yields: key, value
  return enum_for(:map_pairs!) unless block_given?
  replace map_pairs(&block)
end