class Hash
Public Instance Methods
Validates all keys in a hash match *valid_keys
, raising ArgumentError
on a mismatch.
Note that keys are treated differently than HashWithIndifferentAccess, meaning that string and symbol keys will not match.
{ name: 'Rob', years: '28' }.assert_valid_keys(:name, :age) # => raises "ArgumentError: Unknown key: :years. Valid keys are: :name, :age" { name: 'Rob', age: '28' }.assert_valid_keys('name', 'age') # => raises "ArgumentError: Unknown key: :name. Valid keys are: 'name', 'age'" { name: 'Rob', age: '28' }.assert_valid_keys(:name, :age) # => passes, raises nothing
# File lib/sigterm_extensions/core_ext/hash/keys.rb, line 46 def assert_valid_keys(*valid_keys) valid_keys.flatten! each_key do |k| unless valid_keys.include?(k) raise ArgumentError.new("Unknown key: #{k.inspect}. Valid keys are: #{valid_keys.map(&:inspect).join(', ')}") end end end
Removes all blank values from the Hash
in place and returns self. Uses Object#blank?
for determining if a value is blank.
h = { a: "", b: 1, c: nil, d: [], e: false, f: true } h.compact_blank! # => { b: 1, f: true }
# File lib/sigterm_extensions/core_ext/enumerable.rb, line 180 def compact_blank! # use delete_if rather than reject! because it always returns self even if nothing changed delete_if { |_k, v| v.blank? } end
Returns a new hash with self
and other_hash
merged recursively.
h1 = { a: true, b: { c: [1, 2, 3] } } h2 = { a: false, b: { x: [3, 4, 5] } } h1.deep_merge(h2) # => { a: false, b: { c: [1, 2, 3], x: [3, 4, 5] } }
Like with Hash#merge in the standard library, a block can be provided to merge values:
h1 = { a: 100, b: 200, c: { c1: 100 } } h2 = { b: 250, c: { c1: 200 } } h1.deep_merge(h2) { |key, this_val, other_val| this_val + other_val } # => { a: 100, b: 450, c: { c1: 300 } }
# File lib/sigterm_extensions/core_ext/hash/deep_merge.rb, line 16 def deep_merge(other_hash, &block) dup.deep_merge!(other_hash, &block) end
Same as deep_merge
, but modifies self
.
# File lib/sigterm_extensions/core_ext/hash/deep_merge.rb, line 21 def deep_merge!(other_hash, &block) merge!(other_hash) do |key, this_val, other_val| if this_val.is_a?(Hash) && other_val.is_a?(Hash) this_val.deep_merge(other_val, &block) elsif block_given? block.call(key, this_val, other_val) else other_val end end end
Returns a new hash with all keys converted to strings. This includes the keys from the root hash and from all nested hashes and arrays.
hash = { person: { name: 'Rob', age: '28' } } hash.deep_stringify_keys # => {"person"=>{"name"=>"Rob", "age"=>"28"}}
# File lib/sigterm_extensions/core_ext/hash/keys.rb, line 82 def deep_stringify_keys deep_transform_keys(&:to_s) end
Destructively converts all keys to strings. This includes the keys from the root hash and from all nested hashes and arrays.
# File lib/sigterm_extensions/core_ext/hash/keys.rb, line 89 def deep_stringify_keys! deep_transform_keys!(&:to_s) end
Returns a new hash with all keys converted to symbols, as long as they respond to to_sym
. This includes the keys from the root hash and from all nested hashes and arrays.
hash = { 'person' => { 'name' => 'Rob', 'age' => '28' } } hash.deep_symbolize_keys # => {:person=>{:name=>"Rob", :age=>"28"}}
# File lib/sigterm_extensions/core_ext/hash/keys.rb, line 101 def deep_symbolize_keys deep_transform_keys { |key| key.to_sym rescue key } end
Destructively converts all keys to symbols, as long as they respond to to_sym
. This includes the keys from the root hash and from all nested hashes and arrays.
# File lib/sigterm_extensions/core_ext/hash/keys.rb, line 108 def deep_symbolize_keys! deep_transform_keys! { |key| key.to_sym rescue key } end
Returns a new hash with all keys converted by the block operation. This includes the keys from the root hash and from all nested hashes and arrays.
hash = { person: { name: 'Rob', age: '28' } } hash.deep_transform_keys{ |key| key.to_s.upcase } # => {"PERSON"=>{"NAME"=>"Rob", "AGE"=>"28"}}
# File lib/sigterm_extensions/core_ext/hash/keys.rb, line 63 def deep_transform_keys(&block) _deep_transform_keys_in_object(self, &block) end
Destructively converts all keys by using the block operation. This includes the keys from the root hash and from all nested hashes and arrays.
# File lib/sigterm_extensions/core_ext/hash/keys.rb, line 70 def deep_transform_keys!(&block) _deep_transform_keys_in_object!(self, &block) end
Returns a new hash with all values converted by the block operation. This includes the values from the root hash and from all nested hashes and arrays.
hash = { person: { name: 'Rob', age: '28' } } hash.deep_transform_values{ |value| value.to_s.upcase } # => {person: {name: "ROB", age: "28"}}
# File lib/sigterm_extensions/core_ext/hash/deep_transform_values.rb, line 10 def deep_transform_values(&block) _deep_transform_values_in_object(self, &block) end
Destructively converts all values by using the block operation. This includes the values from the root hash and from all nested hashes and arrays.
# File lib/sigterm_extensions/core_ext/hash/deep_transform_values.rb, line 17 def deep_transform_values!(&block) _deep_transform_values_in_object!(self, &block) end
Returns a hash that includes everything except given keys.
hash = { a: true, b: false, c: nil } hash.except(:c) # => { a: true, b: false } hash.except(:a, :b) # => { c: nil } hash # => { a: true, b: false, c: nil }
This is useful for limiting a set of parameters to everything but a few known toggles:
@person.update(params[:person].except(:admin))
# File lib/sigterm_extensions/core_ext/hash/except.rb, line 10 def except(*keys) slice(*self.keys - keys) end
Removes the given keys from hash and returns it.
hash = { a: true, b: false, c: nil } hash.except!(:c) # => { a: true, b: false } hash # => { a: true, b: false }
# File lib/sigterm_extensions/core_ext/hash/except.rb, line 18 def except!(*keys) keys.each { |key| delete(key) } self end
Removes and returns the key/value pairs matching the given keys.
{ a: 1, b: 2, c: 3, d: 4 }.extract!(:a, :b) # => {:a=>1, :b=>2} { a: 1, b: 2 }.extract!(:a, :x) # => {:a=>1}
# File lib/sigterm_extensions/core_ext/hash/slice.rb, line 21 def extract!(*keys) keys.each_with_object(self.class.new) { |key, result| result[key] = delete(key) if has_key?(key) } end
By default, only instances of Hash
itself are extractable. Subclasses of Hash
may implement this method and return true to declare themselves as extractable. If a Hash
is extractable, Array#extract_options!
pops it from the Array
when it is the last element of the Array
.
# File lib/sigterm_extensions/core_ext/array/extract_options.rb, line 7 def extractable_options? instance_of?(Hash) end
Merges the caller into other_hash
. For example,
options = options.reverse_merge(size: 25, velocity: 10)
is equivalent to
options = { size: 25, velocity: 10 }.merge(options)
This is particularly useful for initializing an options hash with default values.
# File lib/sigterm_extensions/core_ext/hash/reverse_merge.rb, line 12 def reverse_merge(other_hash) other_hash.merge(self) end
Destructive reverse_merge
.
# File lib/sigterm_extensions/core_ext/hash/reverse_merge.rb, line 18 def reverse_merge!(other_hash) replace(reverse_merge(other_hash)) end
Replaces the hash with only the given keys. Returns a hash containing the removed key/value pairs.
hash = { a: 1, b: 2, c: 3, d: 4 } hash.slice!(:a, :b) # => {:c=>3, :d=>4} hash # => {:a=>1, :b=>2}
# File lib/sigterm_extensions/core_ext/hash/slice.rb, line 8 def slice!(*keys) omit = slice(*self.keys - keys) hash = slice(*keys) hash.default = default hash.default_proc = default_proc if default_proc replace(hash) omit end
Returns a new hash with all keys converted to strings.
hash = { name: 'Rob', age: '28' } hash.stringify_keys # => {"name"=>"Rob", "age"=>"28"}
# File lib/sigterm_extensions/core_ext/hash/keys.rb, line 8 def stringify_keys transform_keys(&:to_s) end
Destructively converts all keys to strings. Same as stringify_keys
, but modifies self
.
# File lib/sigterm_extensions/core_ext/hash/keys.rb, line 14 def stringify_keys! transform_keys!(&:to_s) end
Returns a new hash with all keys converted to symbols, as long as they respond to to_sym
.
hash = { 'name' => 'Rob', 'age' => '28' } hash.symbolize_keys # => {:name=>"Rob", :age=>"28"}
# File lib/sigterm_extensions/core_ext/hash/keys.rb, line 25 def symbolize_keys transform_keys { |key| key.to_sym rescue key } end
Destructively converts all keys to symbols, as long as they respond to to_sym
. Same as symbolize_keys
, but modifies self
.
# File lib/sigterm_extensions/core_ext/hash/keys.rb, line 32 def symbolize_keys! transform_keys! { |key| key.to_sym rescue key } end
Private Instance Methods
support methods for deep transforming nested hashes and arrays
# File lib/sigterm_extensions/core_ext/hash/keys.rb, line 114 def _deep_transform_keys_in_object(object, &block) case object when Hash object.each_with_object({}) do |(key, value), result| result[yield(key)] = _deep_transform_keys_in_object(value, &block) end when Array object.map { |e| _deep_transform_keys_in_object(e, &block) } else object end end
# File lib/sigterm_extensions/core_ext/hash/keys.rb, line 127 def _deep_transform_keys_in_object!(object, &block) case object when Hash object.keys.each do |key| value = object.delete(key) object[yield(key)] = _deep_transform_keys_in_object!(value, &block) end object when Array object.map! { |e| _deep_transform_keys_in_object!(e, &block) } else object end end
support methods for deep transforming nested hashes and arrays
# File lib/sigterm_extensions/core_ext/hash/deep_transform_values.rb, line 23 def _deep_transform_values_in_object(object, &block) case object when Hash object.transform_values { |value| _deep_transform_values_in_object(value, &block) } when Array object.map { |e| _deep_transform_values_in_object(e, &block) } else yield(object) end end
# File lib/sigterm_extensions/core_ext/hash/deep_transform_values.rb, line 34 def _deep_transform_values_in_object!(object, &block) case object when Hash object.transform_values! { |value| _deep_transform_values_in_object!(value, &block) } when Array object.map! { |e| _deep_transform_values_in_object!(e, &block) } else yield(object) end end