the12 the12 - 9 months ago 49
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? (

--> what is the return value?)

Given the following code below:

restaurants = []
restaurants <<

def import_line(line)
return self

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

def import_line(line)
return true

What would be the return value on
. Would it be set to
or return the instance (
returns instance)?

In essence, when
exists, which method has priority in determining the return value?

Any help would be greatly appreciated!

Answer Source

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: do |line|
  line + '!'

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.