Class: Cistern::Hash

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

Class Method Summary collapse

Class Method Details

.except(hash, *keys) ⇒ Hash

Returns copy of #hash containing all keys except #keys.

Examples:

Cistern::Hash.except({ :a => 1, :b => 2 }, :a) #=> { :b => 2 }

Returns:

  • (Hash)

    copy of #hash containing all keys except #keys



12
13
14
# File 'lib/cistern/hash.rb', line 12

def self.except(hash, *keys)
  Cistern::Hash.except!(hash.dup, *keys)
end

.except!(hash, *keys) ⇒ Hash

Remove all keys not specified in #keys from #hash in place

Examples:

Cistern::Hash.except({ :a => 1, :b => 2 }, :a) #=> { :b => 2 }

Returns:

See Also:

  • {Cistern{Cistern::Hash{Cistern::Hash#except}


22
23
24
25
# File 'lib/cistern/hash.rb', line 22

def self.except!(hash, *keys)
  keys.each { |key| hash.delete(key) }
  hash
end

.slice(hash, *keys) ⇒ Hash

Returns copy of #hash containing only #keys.

Examples:

Cistern::Hash.slice({ :a => 1, :b => 2 }, :a) #=> { :a => 1 }

Returns:

  • (Hash)

    copy of #hash containing only #keys



5
6
7
# File 'lib/cistern/hash.rb', line 5

def self.slice(hash, *keys)
  keys.each_with_object({}) { |e, a| a[e] = hash[e] if hash.key?(e) }
end

.stringify_keys(object) ⇒ Hash

Copy #hash and convert all keys to strings recursively.

Examples:

Cistern::Hash.stringify_keys(:a => 1, :b => 2) #=> { 'a' => 1, 'b' => 2 }

Returns:

  • (Hash)

    #hash with string keys



32
33
34
35
36
37
38
39
40
41
# File 'lib/cistern/hash.rb', line 32

def self.stringify_keys(object)
  case object
  when Hash
    object.each_with_object({}) { |(k, v), a| a[k.to_s] = stringify_keys(v) }
  when Array
    object.map { |v| stringify_keys(v) }
  else
    object
  end
end