Is there a way to create an array of lambdas or an array of procs in ruby? I've been able to define arrays of each, but I have not been able to figure out the syntax for calling the lambdas/procs in the array.
As a foolish made-up example, consider this:
a = [ 1, 2, 3, 4, 5, 6, 7, 8]
b = [2, 3, 5, 7, 10]
c = [
Proc.new { |x| a.include? x },
Proc.new { |x| true },
Proc.new { |x| b.include? x }
]
def things_checker(element, checks)
z = 0
checks.each do |check|
p z
break unless check(element)
z = z + 1
end
end
things_checker(3, c)
I can't figure out a way to get check(element)
to not be a syntax error.
There are many ways to call a proc
in Ruby. All those will work:
break unless check.call(element)
break unless check.(element)
break unless check[element]
and even:
break unless check === element
IMHO, in the example you provided, the latter is mostly semantically correct. It works because triple-equal, also known as case-equal, is invented to be used in case
statements to check the result of call on the argument for being truthy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With