What is the difference between return
and just putting a variable such as the following:
def write_code(number_of_errors)
One small caution for those coming from other languages. Say you have a function like the OP's, and you make use of the "last thing computed" rule to set your return value automagically:
def write_code(number_of_errors)
if number_of_errors > 1
mood = "Ask me later"
else
mood = "No Problem"
end
end
and let's say you add a debugging (or logging) statement:
def write_code(number_of_errors)
if number_of_errors > 1
mood = "Ask me later"
else
mood = "No Problem"
end
puts "### mood = #{mood}"
end
Now guess what. You've broken your code, because the puts
returns nil, which now becomes the return value from the function.
The solution is to get in the habit of always explicitly putting the return value on the last line, the way the OP did:
def write_code(number_of_errors)
if number_of_errors > 1
mood = "Ask me later"
else
mood = "No Problem"
end
puts "### mood = #{mood}"
mood
end