Class: Hash
- Defined in:
- lib/tfg/support/core_ext/hash/deep.rb,
lib/tfg/support/core_ext/hash/map_values.rb,
lib/tfg/support/core_ext/hash/with_indifferent_equality.rb
Instance Method Summary collapse
-
#==(other) ⇒ Object
Check equality of hashes, considering if difference between string and symbol keys should be observed.
-
#deep ⇒ Object
Allows chaining of keys through nested hashes.
-
#map_values ⇒ Object
Allows you to map the values of a hash.
-
#map_values! ⇒ Object
The same as #map_values, except mutates and returns the original hash.
-
#old_double_equals ⇒ Object
Aliased to original #==.
-
#with_indifferent_equality ⇒ Object
Will return a new hash that does not differentiate between string and symbol keys for equality.
Instance Method Details
#==(other) ⇒ Object
Check equality of hashes, considering if difference between string and symbol keys should be observed. See #with_indifferent_equality.
19 20 21 22 23 24 25 |
# File 'lib/tfg/support/core_ext/hash/with_indifferent_equality.rb', line 19 def ==(other) if other.is_a?(TFG::Support::HashWithIndifferentEquality) other == self else old_double_equals(other) end end |
#deep ⇒ Object
Allows chaining of keys through nested hashes.
hash = {foo: true, bar: {baz: {qux: false}}}
hash.deep[:foo] #=> true
hash.deep[:bar, :baz, :qux] #=> false
When the chain of keys is incomplete nil will be returned.
hash[:bar, :qux] #=> nil
Assignment is also possible, and the key chain will be created if needed.
hash = {}
hash[:foo, :bar] = true
hash #=> {foo: {bar: true}}
27 28 29 |
# File 'lib/tfg/support/core_ext/hash/deep.rb', line 27 def deep TFG::Support::DeepHashAccessor.new(self) end |
#map_values ⇒ Object
Allows you to map the values of a hash. The original keys will be retained.
{foo: 1, bar: 2}.map_values {|value| value * 2 } #=> {foo: 2, bar: 4}
The original hash is not mutated.
10 11 12 13 14 15 16 |
# File 'lib/tfg/support/core_ext/hash/map_values.rb', line 10 def map_values Hash.new.tap do |result| self.each do |key, value| result[key] = yield(value) end end end |
#map_values! ⇒ Object
The same as #map_values, except mutates and returns the original hash.
hash = {foo: 1, bar: 2}
hash.map_values {|value| value * 2 }
hash #=> {foo: 2, bar: 4}
25 26 27 28 29 30 31 |
# File 'lib/tfg/support/core_ext/hash/map_values.rb', line 25 def map_values! self.tap do |hash| hash.each do |key, value| hash[key] = yield(value) end end end |
#old_double_equals ⇒ Object
Aliased to original #==.
14 |
# File 'lib/tfg/support/core_ext/hash/with_indifferent_equality.rb', line 14 alias_method :old_double_equals, :== |
#with_indifferent_equality ⇒ Object
Will return a new hash that does not differentiate between string and symbol keys for equality.
{a: 1} == {"a" => 1}.with_indifferent_equality #=> true
9 10 11 |
# File 'lib/tfg/support/core_ext/hash/with_indifferent_equality.rb', line 9 def with_indifferent_equality TFG::Support::HashWithIndifferentEquality.new(self) end |