Class: Hash

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

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

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

Borrowed from ActiveSupport.



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

def symbolize_keys
  result = self.class.new
  each do |key, val|
    new_key = key.respond_to?(:to_sym) ? key.to_sym : key
    new_value = val.respond_to?(:symbolize_keys) ? val.symbolize_keys : val
    result[new_key] = new_value
  end
  result
end

#symbolize_keys!Object

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

Borrowed from ActiveSupport.



25
26
27
28
29
30
31
32
33
34
# File 'lib/teamdrive_api/core_ext/hash.rb', line 25

def symbolize_keys!
  # we have to use `keys.each` because we can't modify a Hash during `each`
  keys.each do |key|
    new_key = key.respond_to?(:to_sym) ? key.to_sym : key
    val = delete(key)
    new_value = val.respond_to?(:symbolize_keys!) ? val.symbolize_keys! : val
    self[new_key] = new_value
  end
  self
end