Reputation: 525
In the test2
method below, why is the return
keyword needed in order for the method's return to not equal nil
?
In test
, return
isn't required. The last line the program evaluates (true
or false
) becomes the return
def test
x = gets.chomp
if x == 'yes'
true
else
false
end
end
result = test
puts result # PRINTS 'TRUE' OR 'FALSE'
But in test2
, if return
isn't given on the lines indicated, the return value of the method will be nil
.
def test2
while true
reply = gets.chomp.downcase
if (reply == 'yes' || reply == 'no')
if reply == 'yes'
true # RETURN NEEDED HERE
else
false # RETURN NEEDED HERE
end
break
else
puts 'Please answer "yes" or "no".'
end
end
end
result2 = test2
puts result2 # PRINTS NIL
The examples are adapted from Chris Pine's How to Program, where it states the return key is necessary here to quit the loop. But why should this return a value, if the last line to be evaluated is still either true
or false
?
Upvotes: 0
Views: 48
Reputation: 114158
You can use break
to provide a return value for while
:
if reply == 'yes'
break true
else
break false
end
Upvotes: 1
Reputation: 47279
if you don't use return
, the last statement in your method is the while
loop itself, which evaluates to nil
. The result of the if inside your loop is not "carried" over when you break out of the loop
Upvotes: 3