Hello. In this session, we will learn about return.
How can you return a value
from a block or method?
And what are the default return values?
There are four cases to study:
a method which uses the caret to return,
a method without the caret,
a block with the caret,
and a block without the caret.
In a method,
if you use the caret to return a value,
here, it will return
a specific value.
It will exit the method.
If I don't use the caret,
the method returns self by default.
This part is optional. You don't usually write it.
The return value of a block is its last expression.
In the case of this block,
between these, I have a block
which takes a value x as a parameter.
I add 33 to x.
The value, the result of this expression x+33
is not used, so it was erased.
The following instruction is x+2, so I add 2 to the value x.
As it's the block's last expression,
its value
represents the return value of the block.
So my block, value:5.
It means I execute the block
with x taking the value 5.
So I compute 33+5;
the result gets erased, since it's useless.
5+2 gives the value 7
which is used as the block's return value.
So the entire expression's value is 7.
If I use the caret in a block,
the behavior is totally different from a method.
You shouldn't expect the block to be terminated,
but the method.
Let's look at the example of the method factorial
in the class Integer.
There's one return here and one there.
These two returns terminate the method's execution.
So if the receiver self is zero
during the execution of the method,
the block is executed,
1 is immediately returned, and the method will terminate.
So the method returns 1.
return is not used to terminate the block but the embracing method.
In the second example, if self is bigger than zero,
you compute with a recursive call
and immediately return the result.
So the method doesn't continue to execute
when self is bigger than zero.
In the other cases, if you reach the third instruction,
you get an error message, meaning that the receiver is a negative number.
You should remember
that the caret allows you to terminate the method
whether caret is located in the method or in the block in the method.
The caret always terminates the method
and returns a value specified after the caret.
By default, a method returns self.
It's useless to write method self at the end
as it is the value which is returned by default.
A block returns the result of its last expression.