Sha256: 4bcac1505d0a62a6bec30ba3ce9d5a8cecc04f353798b3460fa20b8b60313a3f

Contents?: true

Size: 506 Bytes

Versions: 6

Compression:

Stored size: 506 Bytes

Contents

class Hash

  # Take a subset of the hash, based on keys given or a block
  # that evaluates to true for each hash key.
  #
  #   {'a'=>1, 'b'=>2}.subset('a')            #=> {'a'=>1}
  #   {'a'=>1, 'b'=>2}.subset{|k| k == 'a' }  #=> {'a'=>1}
  #
  # CREDIT: Alexey Petrushin
  def subset(keys=nil, &block)
    h = {}
    if keys
      self.each do |k, v|
        h[k] = v if keys.include?(k)
      end
    else
      self.each do |k, v|
        h[k] = v if block.call(k)
      end
    end
    h
  end

end

Version data entries

6 entries across 5 versions & 1 rubygems

Version Path
facets-2.9.3 lib/core/facets/hash/subset.rb
facets-2.9.2 lib/core/facets/hash/subset.rb
facets-2.9.2 src/core/facets/hash/subset.rb
facets-2.9.1 lib/core/facets/hash/subset.rb
facets-2.9.0 lib/core/facets/hash/subset.rb
facets-2.9.0.pre.2 lib/core/facets/hash/subset.rb