legendary_rob
legendary_rob

Reputation: 13012

Ruby retry Array#each loop

I have an array of lambda's i would like to run all of the lamba's at the same time, the array can have any number of lamba's this makes it hard. Since you can only enumerate through an array.

def detect_int(*args)
  return 1 if args.empty?

  n = 1
  args.each do |lam|
     until lam.call(n) do
       n += 1
     end
     retry if lam.call(n) == false
  end
  n
end

This method should work in theory, it should increase the count till lam1.call(n) returns true. then it will move to the next lam, if lam2.call(n) returns false it should retry the args.each loop with the incremented n starting at lam1 again. and so on.

Only i am getting an SyntaxError: (irb):76: Invalid retry how would you retry that each loop so that it will start it from the beginning

I was reading up on ruby loops and the retry method here. mine seems to fit the syntax correctly, but because its a loop within a loop it can get confusing. currently its sitting in the args loop which is the loop i would like to reset.

Upvotes: 2

Views: 895

Answers (2)

legendary_rob
legendary_rob

Reputation: 13012

Here is another way of doing it. Once every instance of args is true it will only break the loop. this is dangerous because it could never satisfy the loop and go on indefinitely

n = 1
while true do
  args.all? { |lam| lam.call(n) } and return n
  n += 1
end

Upvotes: 0

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

Since retry is a ruby keyword, parser wants to see either a native loop or a begin-rescue-end condition around. There is no one and the parser got stuck (Array#each is not a ruby loop, it’s an invocation of plain ruby method on array instance.) The possible solution would be:

args.each do |lam|
  begin # grant parser with a scope
    until lam.call(n) do
      n += 1
    end
    raise if lam.call(n) == false
  rescue
    retry
  end
end

Upvotes: 3

Related Questions