class Hash

Public Instance Methods

map_keys() { |key| ... } click to toggle source

Returns a new hash which is a copy of the current hash but each key 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_keys { |k| k*2 } #=> {'aa'=>1, 'bb'=>2}
{'a'=>1, 'b'=>2}.map_keys { "cat" }   #=> {'cat'=>2}

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

# File lib/hashmap.rb, line 58
def map_keys &block # :yields: key
  return enum_for(:map_keys) unless block_given?
  hsh = {}
  each do |k, v|
    hsh[ yield k ] = v
  end
  hsh
end
map_keys!() { |key| ... } click to toggle source

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

If block returns duplicate keys, they will be overwritten in turn.

See: map_keys

# File lib/hashmap.rb, line 74
def map_keys! &block # :yields: key
  return enum_for(:map_keys!) unless block_given?
  replace map_keys(&block)
end
map_pairs() { |key, value| ... } click to toggle source

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.

# 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!() { |key, value| ... } click to toggle source

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

See: map_pairs

# 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
map_values() { |value| ... } click to toggle source

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

{'a'=>1, 'b'=>2}.map_values { |v| v*2 } #=> {'a'=>2, 'b'=>4}
{'a'=>1, 'b'=>2}.map_values { "cat" }   #=> {'a'=>"cat", 'b'=>"cat"}

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

# File lib/hashmap.rb, line 18
def map_values &block # :yields: value
  return enum_for(:map_values) unless block_given?
  hsh = {}
  each do |k, v|
    hsh[k] = yield v
  end
  hsh
end
map_values!() { |value| ... } click to toggle source

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

See: map_values

# File lib/hashmap.rb, line 32
def map_values! &block # :yields: value
  return enum_for(:map_values!) unless block_given?
  replace map_values(&block)
end