Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/core-ext/hash.rb
Instance Method Summary collapse
-
#only(*keys) ⇒ Object
Returns a new hash containing only the keys specified that exist in the current hash.
- #symbolize_keys ⇒ Object
Instance Method Details
#only(*keys) ⇒ Object
Returns a new hash containing only the keys specified that exist in the current hash.
{:a => '1', :b => '2', :c => '3'}.only(:a, :c)
# => {:a => '1', :c => '3'}
Keys that do not exist in the original hash are ignored.
9 10 11 12 13 14 |
# File 'lib/core-ext/hash.rb', line 9 def only(*keys) inject( {} ) do |new_hash, (key, value)| new_hash[key] = value if keys.include?(key) new_hash end end |
#symbolize_keys ⇒ Object
16 17 18 19 20 21 |
# File 'lib/core-ext/hash.rb', line 16 def symbolize_keys inject({}) do |, (key, value)| [(key.to_sym rescue key) || key] = value end end |