How to jump to a line in ruby
How to jump to a line in ruby
I'm doing a pwd generator in ruby and when I arrive at a certain point of the code I need to return back if the user says that he want to retry to generate the pwd.
print "do you want to retry to generate the password? [y/n]"
retrypwd = gets.chomp
if retrypwd == y
(code to jump to some lines ago)
elsif retrypwd == n
print "Ok, It'll be for the next time"
end
next
break
the line if have to come back is about an hundred lines back so I can't do this
– Gregorio Pompei
Sep 15 '18 at 17:48
The distance doesn't matter. If the logic has to be repeated, it has to be repeated now matter how convoluted it is. Conversely, if you're doing a lot of unrelated stuff in between you should rethink your logic.
– pjs
Sep 15 '18 at 17:49
ok thanks. I'll do it
– Gregorio Pompei
Sep 15 '18 at 17:52
1 Answer
1
The trick is to use a loop and break it or repeat it according to your expectations:
loop
def try_again?
loop do
print "Would you like to try again? Y/N"
again = gets.chomp.capitalize
case (again)
when 'N'
return false
when 'Y'
return true
else
puts "Huh? I don't know what that means."
end
end
end
Then you can incorporate this into your main program:
begin
try_password
end while try_again?
You will keep trying passwords until try_again? returns false, which happens if you type "N".
try_again?
false
Some Rubiests don't like returning from a loop. To please them you could replace
return false (true) with break false (true).– Cary Swoveland
Sep 16 '18 at 18:10
return false
true
break false
true
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy
Embed the logic in a loop and short-circuit with
nextor escape withbreak.– pjs
Sep 15 '18 at 17:44