Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/chinese_vocab/core_ext/hash.rb

Instance Method Summary collapse

Instance Method Details

#delete_keys(*keys) ⇒ Object

Returns a copy of self with *keys removed.



6
7
8
9
10
11
12
13
# File 'lib/chinese_vocab/core_ext/hash.rb', line 6

def delete_keys(*keys)
  hash = self.dup

  keys.each do |key|
    hash.delete(key)
  end
  hash
end

#delete_keys!(*keys) ⇒ Object

Remove *keys from self



16
17
18
19
20
# File 'lib/chinese_vocab/core_ext/hash.rb', line 16

def delete_keys!(*keys)
  keys.each do |key|
    self.delete(key)
  end
end

#slice(*keys) ⇒ Hash

Note:

keys in ‘keys` not present in `self` are silently ignored.

Creates a sub-hash from ‘self` with the keys from `keys`

Returns:

  • (Hash)

    a copy of ‘self`.



25
26
27
# File 'lib/chinese_vocab/core_ext/hash.rb', line 25

def slice(*keys)
  self.select { |k,v| keys.include?(k) }
end

#slice!(*keys) ⇒ Object



29
30
31
32
33
34
# File 'lib/chinese_vocab/core_ext/hash.rb', line 29

def slice!(*keys)
  sub_hash = self.select { |k,v| keys.include?(k) }
  # Remove 'keys' form self:
  self.delete_keys!(*sub_hash.keys)
  sub_hash
end