Class: Hash

Inherits:
Object show all
Defined in:
lib/nutella/core_ext/hash.rb

Instance Method Summary collapse

Instance Method Details

#slice(*keys) ⇒ Hash Also known as: grab

Grab the given keys out of a hash.

Examples:

Selects two keys out of a hash

{ a: 1, b: 2, c: 3, d: 4 }.slice :a, :c  # => { a: 1, c: 3 }

Limits an options hash to valid keys before passing to a method

def search(criteria = {})
  criteria.assert_valid_keys(:mass, :velocity, :time)
end

search(options.slice(:mass, :velocity, :time))def slice(*keys)

Splats an array of keys before passing to the #search method above

valid_keys = [:mass, :velocity, :time]
search(options.slice(*valid_keys))

Parameters:

  • keys (*Object)

    the keys to slice out of the hash

Returns:

  • (Hash)

    the key/value pairs that exist in *keys



20
21
22
# File 'lib/nutella/core_ext/hash.rb', line 20

def slice(*keys)
  select { |k, v| keys.include? k }
end

#slice!(*keys) ⇒ Hash Also known as: grab!

Acts on the hash as described in Hash#slice, but modifies the hash in place.

Examples:

Demonstrates the action and its return value

test = { a: 1, b: 2, c: 3, d: 4 }
test.slice! :a, :c  # => { b: 2, d: 4 }
test                # => { a: 1, c: 3 }

Parameters:

  • keys (*Object)

    the keys to slice out of the hash

Returns:

  • (Hash)

    the removed key/value pairs



35
36
37
38
# File 'lib/nutella/core_ext/hash.rb', line 35

def slice!(*keys)
  replace((original = self.dup).slice *keys)
  original.reject { |k, v| keys.include? k }
end