3

如果我对此代码运行下面的测试,它会返回

 ALERT: an event that always happens

我希望它也能放

 ALERT: an event that never happens

但事实并非如此。我认为差异的原因是各自测试中的“真”和“假”,但我不明白为什么“真”或“假”在这种情况下会有所不同。方法“事件”说

puts "ALERT: #{name}" if yield

如果测试的结果可以解释为“真”在这种情况下等于“产量”,而“假”则不然,那么“假”如何否定“产量”?

问题:'if yield' 是否意味着'yield if block 评估为真'?

代码

def event(name)
  puts "ALERT: #{name}" if yield
end

Dir.glob('*events.rb').each {|file| load file }

测试

event "an event that always happens" do
  true                     
end

event "an event that never happens" do
  false                       
end

输出

ALERT: an event that always happens
4

2 回答 2

4

这可能会有所帮助。

def event(name)
  val = yield
  puts val.inspect
  puts "ALERT: #{name}" if val == "donald"
end

event "an event that always happens" do
  "donald"
end

event "an event that never happens" do
  "duck"
end

印刷

"donald"
ALERT: an event that always happens
"duck"

基本上,yield 的返回值是块中最后评估的值。这就是 if 语句中用作标准的内容。

于 2012-12-07T04:49:16.670 回答
2

问题:'if yield' 是否意味着'yield if block 评估为真'?

不,if yield意思是if((执行块的结果)),也就是说块总是被求值,它的结果作为if语句的条件。

puts "..." if yield意思是“只有当真时才放”。它相当于

if yield
then
    puts "ALERT: #{name}"

这就是为什么你只看到一个输出。在第二次事件调用中,由于if false. 试试这个 :

def event(name)
    result = yield
    puts "the block is #{result}"
    puts "ALERT: #{name}" if result
end

$ ruby -w t.rb 
the block is true
ALERT: an event that always happens
the block is false
$
于 2012-12-07T08:02:32.600 回答