【问题标题】:Block not called in Ruby [duplicate]Ruby中未调用块[重复]
【发布时间】:2015-04-05 04:25:22
【问题描述】:

我试过这段代码:

def m
  return yield if block_given?
  "no block"
end

puts m do
  x = 2
  y = 3
  x*y
end

为什么输出是“无块”? 我将块构建到 m 的方式有什么问题? {"testing"} 会起作用。

【问题讨论】:

标签: ruby


【解决方案1】:

给puts加括号

puts(m do
  x = 2
  y = 3
  x * y
end)

输出为 6。

你的代码相当于

puts(m) do 
  x = 2
  y = 3
  x * y
end

【讨论】:

  • 谢谢。但是为什么 puts m {"testing"} 会起作用?
  • 我现在知道了。谢谢:)
【解决方案2】:

删除puts:

def m
  return yield if block_given?
  "no block"
end

m do
  x = 2
  y = 3
  x*y
end

它将始终返回 m 块中的最后一条语句。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-14
    • 2017-01-11
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多