Procs array or lambdas array

Is there a way to create a lambdas array or a procs array in ruby? I was able to define the arrays of each, but I could not understand the syntax of calling lambdas / procs in the array.

As a silly compiled 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 cannot figure out how to get check(element), so as not to be a syntax error.

+4
source share
4 answers

There are many ways to call procin Ruby. All of them will work:

break unless check.call(element)
break unless check.(element)
break unless check[element]

and even:

break unless check === element

IMHO, , , . , , case-equal, case .

+4

call proc/lambda:

def things_checker(element, checks)
  z = 0
  checks.each do |check|
    p z
    break unless check.call(element)
    z = z + 1
  end
end
+3

lambda / proc can be called with #[]and#call

a = Proc.new { |x| x > 10 }
a[11] # => true
a.call(9) # => false
+3
source

You just need extra .

break unless check.(element)

test run:

$ ruby
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)

0
1
2
+2
source

Source: https://habr.com/ru/post/1627891/


All Articles