当条件为假时,您的Range#+
方法返回。这是发生的事情:nil
if
class Range
def +(range)
puts "me: #{self}"
puts "him: #{range}"
res = (self.begin..range.end) if self.end < range.end && range.include?(self.end)
puts "returning #{res.inspect}"
res
end
end
ary = [(1..2), (1..3), (3..4), (0..9)]
buf = ary[0]
i = 0
while i < ary.size
buf = buf + ary[i]
i+=1
end
# >> me: 1..2
# >> him: 1..2
# >> returning nil
解决方案?
停止制作单一循环并使用标准库的强大功能。当您想通过手动跟踪/更新当前索引来迭代集合时,100 次中有 99 次 - 这是一个坏主意。当你是新人时 - 它是 100 of 100。
ary = [(1..2), (1..3), (3..4), (0..9)]
ary.reduce(:+) # => 1..9
# >> me: 1..2
# >> him: 1..3
# >> returning 1..3
# >> me: 1..3
# >> him: 3..4
# >> returning 1..4
# >> me: 1..4
# >> him: 0..9
# >> returning 1..9