On Wed, Dec 14, 2011 at 3:05 AM, Sam D. [email protected]
wrote:
to change the list of rules/conditions each time I want to call this
method.
But what is the desired output? That’s crucial for the solution (see
below).
Nothing pretty or fancy here, but seems to do it? Note, I think the hash
array_of_lambda_conditions = [lambda {|x| x == 2}, lambda {|x| x == 5 and x
== 5}, lambda {|x| x != 1}]
Why “more hoops”? There is no point in having conditions in Strings
if they are constant in the script. There is no need for eval here.
Please note that an more recent versions of Ruby (at least 1.9.3)
lamba implements operator === which is reasonable because then you can
use a lambda as condition in a case expression and with
Enumerable#grep:
irb(main):004:0> pos = lambda {|x| x >= 0}
=> #<Proc:0x100e300c@(irb):4 (lambda)>
irb(main):005:0> vals = [-10,-5,0,5,10]
=> [-10, -5, 0, 5, 10]
irb(main):007:0> vals.each {|v| p v, pos[v], pos === v; case v;when
pos;puts “pos”;else puts “not” end}
-10
false
false
not
-5
false
false
not
0
true
true
pos
5
true
true
pos
10
true
true
pos
=> [-10, -5, 0, 5, 10]
There do exists ways to do this already, e.g. assuming that conditions
are in an array of lambdas:
get all which satisfy all conditions
items.select {|x| conditions.all? {|c| c[v]}}
get first which satisfies all conditions
items.find {|x| conditions.all? {|c| c[v]}}
get all which satisfy any condition
items.select {|x| conditions.any? {|c| c[v]}}
get first which satisfies any condition
items.find {|x| conditions.any? {|c| c[v]}}
See also Enumerable#reject etc.
Kind regards
rober