Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of procs or array of lambdas

Tags:

ruby

lambda

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.

like image 538
Darth Egregious Avatar asked Dec 11 '22 18:12

Darth Egregious


1 Answers

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.

like image 80
Aleksei Matiushkin Avatar answered Dec 30 '22 21:12

Aleksei Matiushkin