ruby - 为什么 STDOUT 在 Ruby 中只显示一次返回的消息?

标签 ruby lambda return

我刚开始使用 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/

相关文章:

php - return true 不返回或我的 else 声明不起作用?

ruby - 如何使用 Ruby 和 Mechanize 解析格式错误的 HTML

ruby - 从 Watir/Ruby 中的 webtable 中提取文本

ruby - 在文件中添加新行?

javascript - 如何在 Javascript 中将数据返回到原始调用者函数?

json - 使用Spring的mockMvc,如何检查返回的数据是否包含字符串的一部分?

ruby-on-rails - 加载 Rails 3 应用程序的一部分

javascript - 关于在 AWS NodeJS 上使用 TypeScript。 (获取 TS 而不是 JS 的堆栈跟踪)

python - AWS lambda : Using executable with python

vb.net - 我如何在 VB.net 中编写这个 lambda 选择方法?