新手问题 yield

impzx · January 15, 2014 · Last by impzx replied at January 15, 2014 · 2106 hits

class Array def one_by_one for i in 0..size yield(self[i]) end puts end end

arr = [1,3,5,7,9]

arr.one_by_one {|h| print (h*h)}

写的实例代码 报错如下: 19254981one_by_one.rb:12:in block in <main>': undefined method*' for nil:NilClass (NoMethodError) from one_by_one.rb:4:in block in one_by_one' from one_by_one.rb:3:ineach' from one_by_one.rb:3:in one_by_one' from one_by_one.rb:12:in'

好奇,为啥*没有了?

求缩进……………………你现在 one_by_one 传出的量是 0..#{size},不是数组里面的内容……

#1 楼 @cassiuschen 多谢,明白了。

#1 楼 @cassiuschen 不对啊|h|的值应该依次是 1.3,5,7,9.

#3 楼 @impzx 我知道了。不是传入值不对,是 0..size 应该写成 0...size

找到问题了……你在定义 0..size 的时候多了一个,应该是到 size-1 结束。所以最后一个传进 yield 的 h 是 NilClass 的……你可以写arr.one_by_one{|h| print h.class}发现这个问题

#5 楼 @cassiuschen 是这样的。所以改成 0...size。

You need to Sign in before reply, if you don't have an account, please Sign up first.