the12 the12 - 28 days ago 10
Ruby Question

When method chaining, how can you determine which return value will be returned?

I am wondering if a class or any variable is chained to one or more methods? Which return value would it give? (

Class.method1.method2
--> what is the return value?)

Given the following code below:

restaurants = []
restaurants << Restaurant.new.import_line(line.chomp)

def import_line(line)
return self
end


In this case, both methods (
new
and
import_line(line)
return the instance, so I know the instance gets put into the array. I am curious though if
import_line(line)
, returned something like
true


def import_line(line)
return true
end


What would be the return value on
Restaurant.new.import_line(line.chomp)
. Would it be set to
true
or return the instance (
.new
returns instance)?

In essence, when
Class.method1.method2
or
Variable.method1.method2
exists, which method has priority in determining the return value?

Any help would be greatly appreciated!

Answer

The return value is always the last thing in the chain, no exceptions. The result is not necessarily the thing you'd expect, though, as the last thing in the chain might do some tricky stuff.

For example, just to be clear:

Restaurant.new.import_line do |line|
  line + '!'
end

There's no obligation here for import_line to return the result of that block, and it's often the case that it won't.

You can also have occasions where the thing you're chaining switches completely and catches you off guard so you have to be sure about the return values from each function in the chain you're calling.

Example here:

"help!".gsub!(/!/, '?').length
# => 5

"help?".gsub!(/!/, '?').length
#! NoMethodError: undefined method `length' for nil:NilClass

In this case gsub! returns the string if and only if a change was made, otherwise nil, which means you can't chain it in that case.

Comments