Sha256: d18f642c91e970d5c18e4c9253a71c7fef5b45c825cf4573ddd27ccb307007a6

Contents?: true

Size: 1.4 KB

Versions: 20

Compression:

Stored size: 1.4 KB

Contents

=begin rdoc
  Hash extentions
=end
class Hash
    
  # Return a hash of all the elements where the block evaluates to true
  def choose(&block)
    Hash[*self.select(&block).inject([]){|res,(k,v)| res << k << v}]
  end
  
  # Computes the difference between two hashes
  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
  
  def merge_if!(k, v)
    self[k] = v if v
    self
  end
  
  # 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.
  # >> {'Placement' => {'AvailabilityZone'=>"us-east-1a"} }.symbolize_keys(:snake_case)
  # => {:placement=>{:availability_zone=>"us-east-1a"}}  
  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
    
  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  
end

Version data entries

20 entries across 20 versions & 1 rubygems

Version Path
poolparty-1.6.9 lib/core/hash.rb
poolparty-1.6.8 lib/core/hash.rb
poolparty-1.6.7 lib/core/hash.rb
poolparty-1.6.6 lib/core/hash.rb
poolparty-1.6.5 lib/core/hash.rb
poolparty-1.6.4 lib/core/hash.rb
poolparty-1.6.3 lib/core/hash.rb
poolparty-1.6.2 lib/core/hash.rb
poolparty-1.6.1 lib/core/hash.rb
poolparty-1.6.0 lib/core/hash.rb
poolparty-1.5.0 lib/core/hash.rb
poolparty-1.4.8 lib/core/hash.rb
poolparty-1.4.7 lib/core/hash.rb
poolparty-1.4.6 lib/core/hash.rb
poolparty-1.4.5 lib/core/hash.rb
poolparty-1.4.4 lib/core/hash.rb
poolparty-1.4.3 lib/core/hash.rb
poolparty-1.4.2 lib/core/hash.rb
poolparty-1.4.1 lib/core/hash.rb
poolparty-1.4.0 lib/core/hash.rb