-2

我想按照一些规则连接范围。在我尝试循环执行之前,它工作正常。这是代码。

class Range
  def +(range)
    (self.begin..range.end) if self.end < range.end && range.include?(self.end)
  end
end

ary = [(1..2), (1..3), (3..4), (0..9)]
buf = ary[0]
i = 0
while i < ary.size
  buf = buf + ary[i] #=>undefined method `+' for nil:NilClass
  i+=1
end
4

1 回答 1

4

当条件为假时,您的Range#+方法返回。这是发生的事情:nilif

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
于 2013-05-27T20:15:35.590 回答