Module: FatCore::Hash
- Included in:
- Hash
- Defined in:
- lib/fat_core/hash.rb
Enumerable Extensions collapse
-
#each_pair_with_flags ⇒ Hash
Yield each key-value pair in the Hash together with two boolean flags that indicate whether the item is the first or last item in the Hash.
Deletion collapse
-
#delete_with_value(v) ⇒ Hash
Remove from the hash all keys that have values == to given value or that include the given value if the hash has an Enumerable for a value.
Key Manipulation collapse
-
#keys_with_value(val) ⇒ Array<Object>
Return all keys in hash that have a value == to the given value or have an Enumerable value that includes the given value.
-
#remap_keys(key_map = {}) ⇒ Hash
Change each key of this Hash to its value in
key_map
. -
#replace_keys(new_keys) ⇒ Hash
Change the keys of this Hash to new_keys, an array of keys of the same size as the Array self.keys.
Instance Method Details
permalink #delete_with_value(v) ⇒ Hash
Remove from the hash all keys that have values == to given value or that include the given value if the hash has an Enumerable for a value
69 70 71 72 73 74 |
# File 'lib/fat_core/hash.rb', line 69 def delete_with_value(v) keys_with_value(v).each do |k| delete(k) end self end |
permalink #each_pair_with_flags ⇒ Hash
Yield each key-value pair in the Hash together with two boolean flags that indicate whether the item is the first or last item in the Hash.
45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/fat_core/hash.rb', line 45 def each_pair_with_flags last_k = size - 1 k = 0 each_pair do |key, val| first = (k == 0 ? true : false) last = (k == last_k ? true : false) yield(key, val, first, last) k += 1 end self end |
permalink #keys_with_value(val) ⇒ Array<Object>
Return all keys in hash that have a value == to the given value or have an Enumerable value that includes the given value.
88 89 90 91 92 93 94 95 96 |
# File 'lib/fat_core/hash.rb', line 88 def keys_with_value(val) result = [] each_pair do |k, v| if self[k] == val || (v.respond_to?(:include?) && v.include?(val)) result << k end end result end |
permalink #remap_keys(key_map = {}) ⇒ Hash
Change each key of this Hash to its value in key_map
. Keys not appearing in
the key_map
remain in the result Hash.
108 109 110 111 112 113 114 115 116 117 118 |
# File 'lib/fat_core/hash.rb', line 108 def remap_keys(key_map = {}) new_hash = {} each_pair do |key, val| if key_map.key?(key) new_hash[key_map[key]] = val else new_hash[key] = val end end new_hash end |
permalink #replace_keys(new_keys) ⇒ Hash
Change the keys of this Hash to new_keys, an array of keys of the same size as the Array self.keys.
131 132 133 134 135 136 |
# File 'lib/fat_core/hash.rb', line 131 def replace_keys(new_keys) unless keys.size == new_keys.size raise ArgumentError, 'replace_keys: new keys size differs from key size' end to_a.each_with_index.map { |(_k, v), i| [new_keys[i], v] }.to_h end |