class Hash

Public Instance Methods

assert_valid_keys(*valid_keys) click to toggle source

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
compact_blank!() click to toggle source

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
deep_merge(other_hash, &block) click to toggle source

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
deep_merge!(other_hash, &block) click to toggle source

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
deep_stringify_keys() click to toggle source

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
deep_stringify_keys!() click to toggle source

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
deep_symbolize_keys() click to toggle source

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
deep_symbolize_keys!() click to toggle source

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
deep_transform_keys(&block) click to toggle source

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
deep_transform_keys!(&block) click to toggle source

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
deep_transform_values(&block) click to toggle source

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
deep_transform_values!(&block) click to toggle source

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
except(*keys) click to toggle source

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
except!(*keys) click to toggle source

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
extract!(*keys) click to toggle source

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
extractable_options?() click to toggle source

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
reverse_merge(other_hash) click to toggle source

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
Also aliased as: with_defaults
reverse_merge!(other_hash) click to toggle source

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
Also aliased as: reverse_update, with_defaults!
reverse_update(other_hash)
Alias for: reverse_merge!
slice!(*keys) click to toggle source

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
stringify_keys() click to toggle source

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
stringify_keys!() click to toggle source

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
symbolize_keys() click to toggle source

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
Also aliased as: to_options
symbolize_keys!() click to toggle source

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
Also aliased as: to_options!
to_options()
Alias for: symbolize_keys
to_options!()
Alias for: symbolize_keys!
with_defaults(other_hash)
Alias for: reverse_merge
with_defaults!(other_hash)
Alias for: reverse_merge!

Private Instance Methods

_deep_transform_keys_in_object(object) { |key| ... } click to toggle source

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
_deep_transform_keys_in_object!(object) { |key| ... } click to toggle source
# 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
_deep_transform_values_in_object(object) { |object| ... } click to toggle source

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
_deep_transform_values_in_object!(object) { |object| ... } click to toggle source
# 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