Class: Hash

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

Overview

taken from activesupport-4.1.7/lib/active_support/core_ext/hash/keys.rb

Instance Method Summary collapse

Instance Method Details

#symbolize_keysObject Also known as: to_options

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


33
34
35
# File 'lib/ustyle/hash.rb', line 33

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

#symbolize_keys!Object Also known as: to_options!

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



40
41
42
# File 'lib/ustyle/hash.rb', line 40

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


9
10
11
12
13
14
15
# File 'lib/ustyle/hash.rb', line 9

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.



19
20
21
22
23
24
# File 'lib/ustyle/hash.rb', line 19

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