Sha256: e1dad50f59ef005bbe98104c5c1d212d71a9fef950582990bada781a6cd0318e

Contents?: true

Size: 603 Bytes

Versions: 3

Compression:

Stored size: 603 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, &block)
    h = {}

    if block
      raise ArgumentError, "subset arguments and block are exclusive parameters" unless keys.empty?
      each do |k, v|
        h[k] = v if block.call(k)
      end
    else
      each do |k, v|
        h[k] = v if keys.include?(k)
      end
    end

    return h
  end

end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
facets-glimmer-3.2.0 lib/core/facets/hash/subset.rb
facets-3.1.0 lib/core/facets/hash/subset.rb
facets-3.0.0 lib/core/facets/hash/subset.rb