简体   繁体   中英

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?

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, ie, "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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM