File: subset.rb

package info (click to toggle)
ruby-facets 2.9.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 9,824 kB
  • sloc: ruby: 25,483; xml: 90; makefile: 20
file content (24 lines) | stat: -rw-r--r-- 506 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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