Module: Footing::Hash

Defined in:
lib/extensions/hash.rb

Instance Method Summary collapse

Instance Method Details

#adjust_values! {|value| ... } ⇒ Object

Adjusts the values of the Hash in place.

Examples:

dict = {:a => 1, :b => 2, :c => 3}
dict.adjust_values! { |v| v.to_s }
dict # => {:a => "1", :b => "2", :c => "3"}

Yields:

  • (value)

    Yields the current value to the block. The result of the block is then assigned to the corresponding key.



49
50
51
# File 'lib/extensions/hash.rb', line 49

def adjust_values!
  each { |k, v| self[k] = yield(v) }
end

#force_encoding!(encoding) {|value| ... } ⇒ Object

Recursively forces all String values to the specified encoding.

Parameters:

  • []

    encoding The encoding to use.

Yields:

  • (value)

    Yields the value after the encoding has been applied.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/extensions/hash.rb', line 25

def force_encoding!(encoding, &block)
  each do |key, value|
    case value
      when String
        # force encoding then strip all non ascii chars
        if block_given?
          self[key] = yield(value.force_encoding(encoding))
        else
          self[key] = value.force_encoding(encoding)
        end
      when Hash then value.force_encoding!(encoding, &block)
    end
  end
end

#rekey(method_name) ⇒ Hash

Rekeys the Hash by invoking a method on the existing keys and uses the return value as the new key.

NOTE: Creates and returns a new Hash.

Example:

h = { [1] => "short", [1,2] => "medium", [1,2,3] => "long" }
h.rekey(:length) # => { 1 => "short", 2 => "medium", 3 => "long" }

Parameters:

  • name (Symbol)

    The method name to invoke on the existing keys.

Returns:

  • (Hash)

    A new Hash that has been re-keyed.



15
16
17
18
19
20
# File 'lib/extensions/hash.rb', line 15

def rekey(method_name)
  inject({}) do |new_hash, (key, value)|
    new_hash[key.send(method_name)] = value
    new_hash
  end
end