Module: Gorillib::Hashlike::Slice
- Included in:
- Hash
- Defined in:
- lib/gorillib/hashlike/slice.rb
Instance Method Summary collapse
-
#except(*rejected) ⇒ Object
Return a copy that excludes the given keys.
-
#except!(*rejected) ⇒ Object
Modifies the hash to exclude the given keys.
-
#extract!(*allowed) ⇒ Object
Removes and returns the key/value pairs matching the given keys.
-
#only(*allowed) ⇒ Hash
Return a copy having only the given keys.
-
#only!(*allowed) ⇒ Object
Retain only the given keys; return self.
-
#slice(*allowed) ⇒ Object
Returns a copy having only the given keys.
-
#slice!(*allowed) ⇒ Object
Retains only the given keys.
Instance Method Details
#except(*rejected) ⇒ Object
Return a copy that excludes the given keys
If the receiver responds to +convert_key+, the method is called on each of the arguments. This allows +except+ to play nice with hashes with indifferent access for instance:
78 79 80 |
# File 'lib/gorillib/hashlike/slice.rb', line 78 def except(*rejected) dup.except!(*rejected) end |
#except!(*rejected) ⇒ Object
Modifies the hash to exclude the given keys
86 87 88 89 |
# File 'lib/gorillib/hashlike/slice.rb', line 86 def except!(*rejected) rejected.each{|key| delete(key) } self end |
#extract!(*allowed) ⇒ Object
Removes and returns the key/value pairs matching the given keys.
58 59 60 |
# File 'lib/gorillib/hashlike/slice.rb', line 58 def extract!(*allowed) slice!(* self.keys-allowed) end |
#only(*allowed) ⇒ Hash
Return a copy having only the given keys
99 100 101 |
# File 'lib/gorillib/hashlike/slice.rb', line 99 def only(*allowed) dup.only!(*allowed) end |
#only!(*allowed) ⇒ Object
Retain only the given keys; return self
111 112 113 114 |
# File 'lib/gorillib/hashlike/slice.rb', line 111 def only!(*allowed) allowed.map!{|key| convert_key(key) } if respond_to?(:convert_key, true) keep_if{|key, val| allowed.include?(key) } end |
#slice(*allowed) ⇒ Object
Returns a copy having only the given keys
If you have an array of keys you want to limit to, splat them:
valid_keys = [:mass, :velocity, :time] search(options.slice(*valid_keys))
Note: Compatible with Rails 4.0 Active Support
22 23 24 25 26 27 |
# File 'lib/gorillib/hashlike/slice.rb', line 22 def slice(*allowed) allowed.map!{|key| convert_key(key) } if respond_to?(:convert_key, true) hash = self.class.new allowed.each{|key| hash[key] = self[key] if has_key?(key) } hash end |
#slice!(*allowed) ⇒ Object
Retains only the given keys. Returns a copy containing the removed key/value pairs.
40 41 42 43 44 45 46 |
# File 'lib/gorillib/hashlike/slice.rb', line 40 def slice!(*allowed) allowed.map!{|key| convert_key(key) } if respond_to?(:convert_key, true) omit = slice(*self.keys - allowed) hash = slice(*allowed) replace(hash) omit end |