Method: Hash#slice
- Defined in:
- lib/core/facets/hash/slice.rb
#slice(*keep_keys) ⇒ Object
Returns a new hash with only the given keys.
h = {:a=>1, :b=>2, :c=>3}
h.slice(:a, :c) #=> {:a=>1, :c=>3}
h.slice(:a, :d) #=> {:a=>1}
9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/core/facets/hash/slice.rb', line 9 def slice(*keep_keys) if block_given? each do |k, v| keep_keys << k if yield(k, v) end end keep_keys.each_with_object({}) do |key, hash| hash[key] = fetch(key) if key?(key) end end |