Monkey Em585
Monkey Em585

Reputation: 25

Why does STDOUT only show the message from one return in Ruby?

I am new to using Ruby. I have been learning through RubyMonk.

I came across this example code:

def a_method
 lambda { return "we just returned from the block" }.call
 return "we just returned from the calling method"
end

puts a_method

The message produced by STDOUT is "we just returned from the calling method". However, if I delete return "we just returned from the calling method" from the code, the message is "we just returned from the block".

Why is it that both messages are not produced with the original code? Is this a RubyMonk thing or is it always like this?

Upvotes: 1

Views: 60

Answers (2)

Yu Hao
Yu Hao

Reputation: 122453

The only output is done by puts a_method, so only the return value of a_method, which is "we just returned from the calling method" is seen in the output.


If the return line were removed, then a_method becomes:

def a_method
  lambda { return "we just returned from the block" }.call
end

Since no explicte return statement is available, the return value of a_method is its last expression, which is the return value of the lambda, i.e, "we just returned from the block".


How to make both strings seen? Try this:

def a_method
  puts lambda { return "we just returned from the block" }.call
  return "we just returned from the calling method"
end

puts a_method

By puts the return value of the lambda, "we just returned from the block" is also there in the output.

Upvotes: 4

Marek Lipka
Marek Lipka

Reputation: 51171

It's because in first case, you swallow the result of your lambda call. You return only "we just returned from the calling method" string, which is put on STDOUT.

Upvotes: 1

Related Questions