Filter que proveee un pequeño DSL
para especificar restricciones que puedan ser usados sobre objetos Enumerable
para filtrar los elementos producidos por el objeto Enumerable:
19 f = Filter.new
20 f.constraint { |x| x > 10 } .and { |x| x.even? } .and { |x| x % 3 == 0 }
21
22 puts (8..24).select(&f)
Del uso del objeto Filter deducimos que los objetos Filter debe tener
métodos
constraint (línea 20)
and (línea 20)
constraint devuelve un
objeto Filter, lo mismo que and
to_proc (línea 22)
[~/srcLPP/rubytesting/ruby_best_practices/chapter5_functional_programming_techniques]$ ruby filter.rb 12 18 24Este es el código de la clase:
[~/srcLPP/rubytesting/ruby_best_practices/chapter5_functional_programming_techniques]$ cat -n filter.rb
1 class Filter
2 def initialize
3 @constraints = []
4 end
5
6 def constraint(&block)
7 @constraints << block
8 self
9 end
10 alias and constraint
11
12 def to_proc
13 ->(e) { @constraints.all? { |fn| fn[e] } }
14 end
15
16 end
person.name("Peter").age(21).introduce
self).
self is often referred to simply as chaining.
@constraints.all? { |fn| fn[e] }
passes each element of the collection @constraints
to the given block. The method returns true if the block never returns
false or nil.
Casiano Rodriguez León 2015-01-07