Understanding return values of iterators/enumerables

It is my understanding that method that can be applied to a collection
of objects has a default return value, and that in the absence of an
explicit return value stated by said programmer, the default value will
be returned.

So, for example, the ‘each’ iterator will return the array, but if you
wish it to return something else, you simply put a return statement
within the iterator function.

Is that right?

Not quite. What is implicit is the return value of a method if no
explicit return is given, which defaults to the return value of the last
executed statement.

The method “each” hasn’t got a default return value you can change, its
return value is (with a block) always the array on which it is called.

But consider this code.

def test
[1,2,3].each do |x|
puts x
return true
end
end

Here there is an explicit return statement. This will print “1” and
method test will pre-maturely return true before the iteration finishes.

On the other hand:

def test
[1,2,3].each do |x|
puts x
end
end

Here there is no explicit return statement, and the return value of the
method will be the return value of the last executed statement, ie. the
return value of method each.

If you want the iteration to finish and return a custom value:

def test
[1,2,3].each do |x|
puts x
end
“hello word”
end

This returns the string “hello world”.

Check out ruby’s documentation for return values of library functions:

http://ruby-doc.org/core-2.2.0/Array.html#method-i-each


(*) If you really wanted do, you could overwrite the each method and
modify its return value, but I strongly advise against it.

(**) Some methods expect a block to return a certain value, which will
be the value of the last statement:

[1,2,3].find{|x|x>1}

The block returns true if x is greater than 1, and false otherwise. The
method find returns the first element for which the block returns true,
or nil if it never returns true.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs