class Hash

Public Instance Methods

has_keys?(*keys)
Alias for: keys?
keys?(*keys) click to toggle source

Returns whether the hash contains all of the specified keys. This method is similar to Hash#key?, but it accepts several keys.

Arguments

  • keys - keys that needs to be checked in the hash.

Examples

{a: 1, b: 2}.keys?(:a, :b) #=> true
{a: 1, b: 2}.keys?(:a, :c) #=> false
# File core_extensions/hash/inclusion.rb, line 15
def keys?(*keys)
  keys.all? { |key| self.key?(key) }
end
Also aliased as: has_keys?
keys_at(*values) click to toggle source

Returns the array of keys of an occurrence of given values. If the value is not found, returns empty array.

Arguments

  • values - values for which keys are to be retrieved.

Examples

{a: 1, b: 2}.keys_at(1, 2) #=> [:a, :b]
{a: 1, b: 2}.keys_at(1, 3) #=> [:a]
{a: 1, b: 2}.keys_at(3)    #=> []
# File core_extensions/hash/access.rb, line 16
def keys_at(*values)
  select { |_, value| values.include?(value) }.keys
end
slice!(*keys) click to toggle source

Alters the hash by keeping only specified ‘keys` and returns it. If the key is not present, returns empty `Hash`.

Arguments

  • keys - keys to be kept in the original ‘Hash`.

Examples

{name: 'John', age: 30, occupation: 'Engineer', gender: 'Male'}.slice!(:name, :age) #=> {name: 'John', age: 30}
{name: 'John', age: 30, occupation: 'Engineer', gender: 'Male'}.slice!(:address)    #=> {}
# File core_extensions/hash/delete.rb, line 15
def slice!(*keys)
  keep_if { |key, _| keys.include?(key) }
end