Class: Hash
Overview
Hash extentions
Instance Method Summary collapse
-
#choose(&block) ⇒ Object
Return a hash of all the elements where the block evaluates to true.
-
#diff(other, *hsh) ⇒ Object
Computes the difference between two hashes.
- #merge_if!(k, v) ⇒ Object
- #method_missing(sym, *args, &block) ⇒ Object
-
#symbolize_keys!(key_modifier = nil) ⇒ Object
Converts all of the keys to strings can pass in a :key_modifier that will be sent to each key, before being symbolized.
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(sym, *args, &block) ⇒ Object
45 46 47 48 49 50 51 52 53 |
# File 'lib/core/hash.rb', line 45 def method_missing(sym, *args, &block) if has_key?(sym.to_sym) fetch(sym) elsif has_key?(sym.to_s) fetch(sym.to_s) else super end end |
Instance Method Details
#choose(&block) ⇒ Object
Return a hash of all the elements where the block evaluates to true
7 8 9 |
# File 'lib/core/hash.rb', line 7 def choose(&block) Hash[*self.select(&block).inject([]){|res,(k,v)| res << k << v}] end |
#diff(other, *hsh) ⇒ Object
Computes the difference between two hashes
12 13 14 15 16 17 18 19 20 |
# File 'lib/core/hash.rb', line 12 def diff(other, *hsh) o = {} keys.map do |k| if hsh.include?(k) || hsh.empty? other[k] == self[k] ? nil : o.merge!({k => other[k]}) end end.reject {|b| b.nil? } o end |
#merge_if!(k, v) ⇒ Object
22 23 24 25 |
# File 'lib/core/hash.rb', line 22 def merge_if!(k, v) self[k] = v if v self end |
#symbolize_keys!(key_modifier = nil) ⇒ Object
Converts all of the keys to strings can pass in a :key_modifier that will be sent to each key, before being symbolized. This can be usefull if you want to downcase, or snake_case each key. >> => {‘AvailabilityZone’=>“us-east-1a” }.symbolize_keys(:snake_case)
> :placement=>{:availability_zone=>“us-east-1a”}
32 33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/core/hash.rb', line 32 def symbolize_keys!(key_modifier=nil) keys.each{|k| v = delete(k) if key_modifier && k.respond_to?(key_modifier) k = k.send(key_modifier) end self[k.to_sym] = v v.symbolize_keys!(key_modifier) if v.is_a?(Hash) v.each{|p| p.symbolize_keys!(key_modifier) if p.is_a?(Hash)} if v.is_a?(Array) } self end |