Xavier Noria
2/19/2007 1:03:00 PM
On Feb 19, 2007, at 1:44 PM, Derek Teixeira wrote:
> i've been getting confused about what exactly the return statement
> does...
Return means "we are done".
Sometimes when you write a method (I don't know the jargon used in
that book, it may be function, or subroutine, or procedure, ...) you
know somewhere in the middle that _if the code reached that point_ we
do not need to do anything else. For instance, see this method that
says where the given number is positive:
def is_positive?(n)
if n > 0
return true
end
return false
end
That method can be written in different ways, but to depict the
meaning of return: if n is greater than 0, you already know the
answer, so in that point you indicate there's no need to execute more
code, you're ready to give the answer: true. If the execution reaches
that point, the following executable line "return false" will be
ignored altogether, execution is halted.
Return in addition accepts a value to be returned (true/false in the
example), which is considered to be the _result_ of that method call
in such case.
> Along with that confusion on the return function.. i was code tracing
> the code below and i understand it, except for one part, i just don't
> see where the code tells the program to print out the numString. I see
> it telling the program to in the 'one hundred' section, but not at all
> in the teens or single digits?
> def englishNumber number
<snip>
> end
The purpose of that method is to compute and return a _string_, not
to actually _print_ that string.
> puts englishNumber( 0)
Now here you have two calls: first a call to englishNumber( 0), and
then a call to puts. They are executed in that order, and the string
returned by the first call is chained into the second call, so puts
is the one that prints the string.
Does that help? Please do no hesitate to send more questions.
-- fxn