Is an elsif loop possible?

D

Devin Rawlek

Hi Everyone,

I don't know if this is possible as I haven't found anything on google
or in here. Is it possible to have an elsif to be looped?

$Str = gets.chomp
if $Str.to_i < 0
puts 'Sorry you cannot be that weak. Please enter a valid stat.'
elsif $Str.to_i > StartStats.to_i
puts 'You cannot give more stats than what you have available.
Please enter a valid stat.'
else puts 'Your Strength is '+($Str)
end

Is there a way to make this a loop so that if $Str.to_i < 0 it would
restart and ask for an input again? Even if the answer is the same it
would still restart?

I tried setting up a retry and redo but I couldn't get it to work.

Thank you for your time.
 
D

Devin Rawlek

Thank you Steve. That was exactly what I needed.

This works perfectly.

$Str = gets.chomp
$Str.to_i < 0
until $Str.to_i > 0
puts 'Sorry you cannot be that weak. Please enter a valid stat.'
$Str = gets.chomp
end
$Str.to_i > StartStats.to_i
until $Str.to_i < StartStats.to_i
puts 'You cannot give more stats than what you have available. Please
enter a valid stat.'
$Str = gets.chomp
end

That site is an excellent resource.
Thanks again Steve.
 
7

7stud --

Devin Rawlek wrote in post #986991:
Thank you Steve. That was exactly what I needed.

This works perfectly.

$Str = gets.chomp
$Str.to_i < 0

What is that line for? As written it does nothing: the comparison
evaluates to either true or false and then the value is discarded.
until $Str.to_i > 0


Note that any until loop can be written as a while loop:

while $Str.to_i <= 0

and while loops are much clearer in meaning.
 
M

Michael Edgar

and while loops are much clearer in meaning.

That's a purely subjective point to make and, in my opinion, often =
untrue.

while !x.nil?
// body
end

vs.

until x.nil?
// body
end

is a simple example where I like the until version better. Once =
DeMorgan's
law kicks in for certain negations, until loops can become much cleaner. =
Example:

while !x.nil? || y < 0
// body
end

until x.nil? && y >=3D 0
// body
end

I personally think the until loop there is *much* simpler to read.

Michael Edgar
(e-mail address removed)
http://carboni.ca/
 
S

Steve Klabnik

[Note: parts of this message were removed to make it a legal post.]

Agreed, especially in this instance. You want to process until the input is
correct. 'while not' is just awkward.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top