Class: Hash

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

Overview

Rails symbolize keys methods for Hash

Instance Method Summary collapse

Instance Method Details

#symbolize_keysObject



29
30
31
# File 'lib/do_snapshot/core_ext/hash.rb', line 29

def symbolize_keys
  transform_keys { |key| key.to_sym rescue key } # rubocop:disable Style/RescueModifier
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.



35
36
37
# File 'lib/do_snapshot/core_ext/hash.rb', line 35

def symbolize_keys!
  transform_keys! { |key| key.to_sym rescue key } # rubocop:disable Style/RescueModifier
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"}


12
13
14
15
16
17
18
# File 'lib/do_snapshot/core_ext/hash.rb', line 12

def transform_keys
  result = {}
  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.



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

def transform_keys!
  keys.each do |key|
    self[yield(key)] = delete(key)
  end
  self
end