Reputation: 11247
I am learning ruby and computer science topics for the first time. I am reading through the book "Learn to program" By Chris Pine and have a question about an example.
Here is the code:
def ask(question) # new method with paramater question
while true # starts a loop
puts question # puts the question on the screen
reply = gets.chomp.downcase # gets the question and makes it lower case
if (reply == "yes" || reply == "no") # if reply was yes or no
if reply == "yes" # nested if statement if yes answer == true
answer = true # WHAT??
else # the else of the second if
answer = false # WHAT?? why do we care about answer??
end
break # Breaks the Loop
else # the else of the 1st if
puts ' Please answer "yes" or "no".'
end
end
answer # Why is answer here?
end
My question is why do we need "answer"? I don't see how it is having any impact on the loop. The while loop is set to true not answer.
Upvotes: 1
Views: 133
Reputation: 118261
end
answer #Why is answer here?
end
It is there to return the result of answer
(either true
or false
) from the method ask
.
My question is why do we need "answer"?
answer
is needed as per your example to hold the Boolean value which is to be returned when method execution will be completed. Your while
loop is an infinite loop,which can only be broken by the break
statement,when reply
will be having either 'yes'
or 'no'
vlaue.
Upvotes: 0
Reputation: 106410
Ruby returns the last statement it executes. In effect, it's the same as writing
return answer;
...in a language like C or Java.
Upvotes: 4