Class: Hash

Inherits:
Object show all
Defined in:
lib/flappy/patches/hash.rb,
lib/flappy/patches/blank.rb

Instance Method Summary collapse

Instance Method Details

#compactObject

Returns a copy of self with all blank keys removed.

hash = { name: 'Rob', age: '', title: nil }

hash.compact
# => { name: 'Rob' }


10
11
12
# File 'lib/flappy/patches/hash.rb', line 10

def compact
  delete_if { |_, v| v.is_a?(FalseClass) ? false : v.blank? }
end

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


60
61
62
# File 'lib/flappy/patches/hash.rb', line 60

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


48
49
50
# File 'lib/flappy/patches/hash.rb', line 48

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/flappy/patches/hash.rb', line 36

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


20
21
22
23
24
25
26
27
# File 'lib/flappy/patches/hash.rb', line 20

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