Module: NamedArguments::HashExtendedTools
- Defined in:
- lib/named_arguments/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.
- #symbol_keys_as_strings ⇒ Object
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}
75 76 77 78 79 80 81 82 |
# File 'lib/named_arguments/hash_extended_tools.rb', line 75 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).
44 45 46 47 48 49 50 51 |
# File 'lib/named_arguments/hash_extended_tools.rb', line 44 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.
60 61 62 63 64 65 66 |
# File 'lib/named_arguments/hash_extended_tools.rb', line 60 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.
25 26 27 28 29 30 31 32 33 34 |
# File 'lib/named_arguments/hash_extended_tools.rb', line 25 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 self end |
#symbol_keys_as_strings ⇒ Object
84 85 86 87 88 89 90 91 92 |
# File 'lib/named_arguments/hash_extended_tools.rb', line 84 def symbol_keys_as_strings sym_keys = self.keys.select {|k| k.kind_of? Symbol} new_keys = {} sym_keys.each {|k| new_keys[k] = k.to_s} result = dup result.extend HashExtendedTools result.switch_keys new_keys result end |