Module: HashExtendedTools
- Included in:
- NamedArguments
- Defined in:
- lib/hash_extended_tools.rb
Overview
Provides several hash utilities.
Note that you need to extend your hash with this module:
hash = {}
hash.extend HashExtendedTools
hash = hash.exclude :foo, :bar
Or create a new class:
class HashWithExtendedTools < Hash
include HashExtendedTools
end
Instance Method Summary collapse
-
#attributes_as_hash(*attrs) ⇒ Object
Return the given attributes as a hash containing attribute => value pairs.
-
#exclude(*keys_to_exclude) ⇒ Object
Return a new hash not including keys that are contained in
keys_to_exclude. -
#slice(*slice_keys) ⇒ Object
Given an array of keys, return a hash containing the key/value pairs for the matching keys.
-
#switch_keys(args = {}) ⇒ Object
Change keys in a hash.
Instance Method Details
#attributes_as_hash(*attrs) ⇒ Object
Return the given attributes as a hash containing attribute => value pairs.
obj.a = 10
obj.b = 20
attributes_as_hash(:a, :b)
=> {:a => 10, :b => 20}
73 74 75 76 77 78 79 80 |
# File 'lib/hash_extended_tools.rb', line 73 def attributes_as_hash *attrs result = {} attrs.each do |a| v = self.send a result[a] = v unless v.nil? end result end |
#exclude(*keys_to_exclude) ⇒ Object
Return a new hash not including keys that are contained in keys_to_exclude.
Keys that match entries in keys_to_exclude are deleted if either they match as string or a symbol (created with to_sym).
42 43 44 45 46 47 48 49 |
# File 'lib/hash_extended_tools.rb', line 42 def exclude *keys_to_exclude result = self.dup keys_to_exclude.each do |k| result.delete k.to_s result.delete k.to_sym end result end |
#slice(*slice_keys) ⇒ Object
Given an array of keys, return a hash containing the key/value pairs for the matching keys.
Values that are nil are not returned.
58 59 60 61 62 63 64 |
# File 'lib/hash_extended_tools.rb', line 58 def slice *slice_keys result = {} slice_keys.each do |k| result[k] = self[k] unless self[k].nil? end result end |
#switch_keys(args = {}) ⇒ Object
Change keys in a hash.
Pass in a hash of:
old_key => new_key
Any keys matching old_key will be deleted and a new entry created with the same value and the new key.
24 25 26 27 28 29 30 31 32 |
# File 'lib/hash_extended_tools.rb', line 24 def switch_keys args = {} args.each_pair do |old_key, new_key| if self.has_key?(old_key) self[new_key] = self[old_key] delete(old_key) end end end |