On 14/12/11 14:28, Thescholar Thescholar wrote:
> I”Ēm unsure how to explain this one so I'll do my best.
>
> Technically, I would like to pass an array of numbers and an array of
> conditions as parameters in a method. The tricky part is that I would
> like to evaluate each number of that array to each condition of that
> other array.
>
> The reason I would like to achieve something like this is because I plan
> to change the list of rules/conditions each time I want to call this
> method.
>
> Here”Ēs the unworking code so far:
>
> (see attachment)
>
> Thank you in advance for your valuable support! Any help or hyperlinks
> with explanations is greatly appreciated!
>
> Attachments:
> http://www.ruby-forum.com/attachment/6838/array_of_conditions.txt
>
Nothing pretty or fancy here, but seems to do it? Note, I think the hash 
interpolation is a 1.9.x thing.


array_of_numbers = [0, 2, 4, 7, 10, 25]

# these could easily come from a config file/ db/ whatevs
array_of_eval_conditions = [ "(%{number} == 2)", "(%{number} == 5 and 
%{number} == 5)", "(%{number} != 1)"]

# these could too, but would require a few more hoops
array_of_lambda_conditions = [lambda {|x| x == 2}, lambda {|x| x == 5 
and x == 5}, lambda {|x| x != 1}]

# for each number and condition, is it true when eval'ed?
def test_function_with_eval(numbers, conditions)
   numbers.each { |n|
     conditions.each { |c|
       puts ((eval(c%{:number=>n}))?"condition IS MET!":"condition is 
NOT met")
     }
   }
end

# for each number and condition, is it true when called?
def test_function_with_lambdas(numbers, conditions)
   numbers.each { |n|
     conditions.each { |c|
       puts ((c.call(n))?"condition IS MET!":"condition is NOT met")
     }
   }
end


puts "With eval!"
test_function_with_eval(array_of_numbers, array_of_eval_conditions)
puts "With lambdas!"
test_function_with_lambdas(array_of_numbers, array_of_lambda_conditions)


Sam