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:

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

{{ parent.tldr }}

{{ parent.urlSource.name }}