Module: Gorillib::Hashlike::Slice
- Included in:
- Hash
- Defined in:
- lib/gorillib/hashlike/slice.rb
Instance Method Summary collapse
-
#slice(*allowed_keys) ⇒ Object
Slice a hash to include only the given allowed_keys.
-
#slice!(*allowed_keys) ⇒ Object
Replaces the hash with only the given allowed_keys.
Instance Method Details
#slice(*allowed_keys) ⇒ Object
Slice a hash to include only the given allowed_keys. This is useful for limiting an options hash to valid keys before passing to a method:
def search(criteria = {})
assert_valid_keys(:mass, :velocity, :time)
end
search(.slice(:mass, :velocity, :time))
If you have an array of keys you want to limit to, you should splat them:
valid_keys = [:mass, :velocity, :time]
search(.slice(*valid_keys))
17 18 19 20 21 22 |
# File 'lib/gorillib/hashlike/slice.rb', line 17 def slice(*allowed_keys) allowed_keys = allowed_keys.map!{|key| convert_key(key) } if respond_to?(:convert_key) hash = self.class.new allowed_keys.each{|k| hash[k] = self[k] if has_key?(k) } hash end |
#slice!(*allowed_keys) ⇒ Object
Replaces the hash with only the given allowed_keys. Returns a hash containing the removed key/value pairs
32 33 34 35 36 37 38 |
# File 'lib/gorillib/hashlike/slice.rb', line 32 def slice!(*allowed_keys) allowed_keys = allowed_keys.map!{|key| convert_key(key) } if respond_to?(:convert_key) omit = slice(*self.keys - allowed_keys) hash = slice(*allowed_keys) replace(hash) omit end |