Class: Hash

Inherits:
Object show all
Defined in:
lib/flow/core_ext/hash.rb,
lib/flow/core_ext/blank.rb

Instance Method Summary collapse

Instance Method Details

#deep_symbolize_keysObject

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"}}


66
67
68
# File 'lib/flow/core_ext/hash.rb', line 66

def deep_symbolize_keys
  deep_transform_keys { |key| key.to_sym rescue key }
end

#deep_transform_keys(&block) ⇒ Object

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"}}


54
55
56
# File 'lib/flow/core_ext/hash.rb', line 54

def deep_transform_keys(&block)
  _deep_transform_keys_in_object(self, &block)
end

#symbolize_keysObject

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"}


36
37
38
# File 'lib/flow/core_ext/hash.rb', line 36

def symbolize_keys
  transform_keys { |key| key.to_sym rescue key }
end

#symbolize_keys!Object

Destructively convert all keys to symbols, as long as they respond to to_sym. Same as symbolize_keys, but modifies self.



42
43
44
# File 'lib/flow/core_ext/hash.rb', line 42

def symbolize_keys!
  transform_keys!{ |key| key.to_sym rescue key }
end

#transform_keysObject

Returns a new hash with all keys converted using the block operation.

hash = { name: 'Rob', age: '28' }

hash.transform_keys{ |key| key.to_s.upcase }
# => {"NAME"=>"Rob", "AGE"=>"28"}


10
11
12
13
14
15
16
17
# File 'lib/flow/core_ext/hash.rb', line 10

def transform_keys
  return enum_for(:transform_keys) unless block_given?
  result = self.class.new
  each_key do |key|
    result[yield(key)] = self[key]
  end
  result
end

#transform_keys!Object

Destructively convert all keys using the block operations. Same as transform_keys but modifies self.



21
22
23
24
25
26
27
# File 'lib/flow/core_ext/hash.rb', line 21

def transform_keys!
  return enum_for(:transform_keys!) unless block_given?
  keys.each do |key|
    self[yield(key)] = delete(key)
  end
  self
end