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






Embed the logic in a loop and short-circuit with next or escape with break.

– pjs
Sep 15 '18 at 17:44



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

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ

Node.js puppeteer - Use values from array in a loop to cycle through pages