Module: Footing::Hash
- Defined in:
- lib/extensions/hash.rb
Instance Method Summary collapse
-
#adjust_values! {|value| ... } ⇒ Object
Adjusts the values of the Hash in place.
-
#force_encoding!(encoding) {|value| ... } ⇒ Object
Recursively forces all String values to the specified encoding.
-
#rekey(method_name) ⇒ Hash
Rekeys the Hash by invoking a method on the existing keys and uses the return value as the new key.
Instance Method Details
#adjust_values! {|value| ... } ⇒ Object
Adjusts the values of the Hash in place.
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.
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" }
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 |