Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/sc-core-ext/hash.rb
Instance Method Summary collapse
- #camelize_keys ⇒ Object
-
#optionalize ⇒ Object
(also: #without_nil_values)
Returns a hash that is a copy of this one, except that all nil values have been removed, making them essentially “optional” keys.
-
#rename(to) ⇒ Object
Takes a hash whose keys must match keys in this hash.
- #without(*keys) ⇒ Object
- #without_values(*values) ⇒ Object
Instance Method Details
#camelize_keys ⇒ Object
26 27 28 29 30 31 |
# File 'lib/sc-core-ext/hash.rb', line 26 def camelize_keys stringify_keys.rename(inject({}) do |renamed, (key, value)| renamed[key.to_s] = key.to_s.camelize renamed end) end |
#optionalize ⇒ Object Also known as: without_nil_values
Returns a hash that is a copy of this one, except that all nil values have been removed, making them essentially “optional” keys.
20 21 22 |
# File 'lib/sc-core-ext/hash.rb', line 20 def optionalize without_values(nil) end |
#rename(to) ⇒ Object
Takes a hash whose keys must match keys in this hash. Those keys will be renamed to match the corresponding value in the specified hash.
Keys not found are ignored.
Returns self.
Example:
{ :a => 1 }.rename(:a => :b)
=> {:b => 1}
44 45 46 47 48 49 50 |
# File 'lib/sc-core-ext/hash.rb', line 44 def rename(to) merge!(inject({}) do |hash, (old_key, value)| hash[to[old_key] || old_key] = value delete(old_key) hash end) end |
#without(*keys) ⇒ Object
2 3 4 5 6 7 8 |
# File 'lib/sc-core-ext/hash.rb', line 2 def without(*keys) keys.flatten! inject({}) do |hash, (key, value)| hash[key] = value unless keys.include?(key) hash end end |
#without_values(*values) ⇒ Object
10 11 12 13 14 15 16 |
# File 'lib/sc-core-ext/hash.rb', line 10 def without_values(*values) values.flatten! inject({}) do |hash, (key, value)| hash[key] = value unless values.include?(value) hash end end |