Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I jump back to the beginning of a method using 'redo' in Ruby?

Tags:

ruby

redo

In the Poignant Guide this example of the redo keyword is given:

class LotteryTicket
  def self.new_random
    new(rand(25) + 1, rand(25) + 1, rand(25) + 1)
  rescue ArgumentError
    redo
  end
end

It's supposed to keep calling new until all three random numbers are unique. But after I typed this code in and ran it a few times, I got this error: LocalJumpError: unexpected redo. I looked up the redo keyword elsewhere and it looks like it is only supposed to work for loops and iterators. So why did why try to use it like this in his example? How should this method be rewritten to work correctly?

like image 571
Paige Ruten Avatar asked Dec 18 '22 08:12

Paige Ruten


2 Answers

He must have meant to use retry, not redo.

like image 118
vladr Avatar answered Jan 23 '23 13:01

vladr


redo restarts a block:

l = lambda {puts "hi"; redo}
l.call
like image 21
Daniel Tsadok Avatar answered Jan 23 '23 15:01

Daniel Tsadok