我刚开始使用 Ruby。我一直在通过 RubyMonk 学习。
我遇到了这个示例代码:
def a_method
lambda { return "we just returned from the block" }.call
return "we just returned from the calling method"
end
puts a_method
STDOUT 产生的消息是“我们刚刚从调用方法返回”。但是,如果我删除 return "we just returned from the calling method"
从代码中,消息是“我们刚刚从街区返回”。
为什么两条消息都不是用原始代码生成的?这是 RubyMonk 的事情还是总是这样?
最佳答案
唯一的输出是由puts a_method
完成的,所以只有a_method
的返回值,也就是“we just returned from the calling method”
出现在输出中。
如果删除了 return
行,则 a_method
变为:
def a_method
lambda { return "we just returned from the block" }.call
end
由于没有明确的return
语句可用,a_method
的返回值是它的最后一个表达式,即lambda的返回值,即"我们刚从街区回来”
。
如何让两个字符串都可见?试试这个:
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
通过 puts
lambda 的返回值,“我们刚从 block 中返回”
也在输出中。
关于ruby - 为什么 STDOUT 在 Ruby 中只显示一次返回的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29676876/