DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Higher-Order Procedures

02.24.2010
| 1930 views |
  • submit to reddit
        Source: <a href="http://github.com/sandal/rbp-book/raw/gh-pages/pdfs/ch05.pdf">Chapter 5 - Functional Programming Techniques</a> [github.com] (O’Reilly’s Ruby Best Practices) via <a href="http://www.rubyinside.com/free-chapters-ruby-best-practices-3004.html">RubyInside.com</a>

<snip>
class Filter
  def initialize
    @constraints = []
  end
  def constraint(&block)
    @constraints << block
  end
  def to_proc
    lambda { |e| @constraints.all? { |fn| fn.call(e) } }
  end
end

filter = Filter.new
filter.constraint { |x| x > 10 }
filter.constraint { |x| x.even? }
filter.constraint { |x| x % 3 == 0 }

p (8..24).select(&filter) #=> [12,18,24]
</snip>