2013-02-02 34 views
1

CODE-I混乱与产量调用外部块

def sample 
    x = "hi" 
    puts " #{x}" 
    x = yield 
    puts " #{x}" 
end 

在下面的代码block {}从这里=>sample {"hellooo"}称为 yield和分配的 “hellooo” 到x。看起来不错并且如预期的那样。

sample{'helloo'} 
# >> hi 
# >> helloo 

CODE-II

o = Object.new 
def o.each 
    x = yield 
    p x 
    x = yield 
    p x 
    x = yield 
    p x 
end 
e = o.to_enum # => #<Enumerator: #<Object:0x007fd1d20494e8>:each> 

为什么在下面的呼叫与e.next "sample"同样没有发生,作为p没有印刷任何东西?

e.next {"sample"} # => nil 
e.next # => nil 
# >> nil 

编辑(这里如何enum#feed确实与yield帮助改变?)

o = Object.new 
=> #<Object:0x2299d88> 
def o.each 
x = yield   
p x  
x = yield 
p x 
x = yield 
p x 
end 
=> nil 
e=o.to_enum 
=> #<Enumerator: #<Object:0x2299d88>:each> 
e.next 
=> nil 
e.feed "hi" 
=> nil 
e.next 
"hi" 
=> nil 
+1

请在发布代码时多加注意,以确保读者的舒适。这是你最大的利益。原始代码是不可读的IRB混乱。 –

+0

你得到零?因为我得到无限的等待和IRB挂起。 – Linuxios

+0

和一个失控的过程。 – Linuxios

回答

1

next并不需要一个块。所以如果你通过它,它就会忽略它。

使用枚举数的next方法时,无法模拟块中返回的内容。当使用to_enum时,给定each方法的块将始终返回nil,除非以前由feed方法提供的值。

+0

是的!你在说什么,从输出中可以看到,但我的问题是如何防止'next'? – DoLoveSky

+0

@DoLoveSky没有什么是被阻止的。枚举器根本不会返回块中的任何内容。 – sepp2k

+0

请参阅我的**编辑** – DoLoveSky