Over a million developers have joined DZone.

Higher-Order Procedures

·
Source: Chapter 5 - Functional Programming Techniques [github.com] (O’Reilly’s Ruby Best Practices) via RubyInside.com



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]

Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}