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
Higher-Order Procedures
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>





