数组元素循环为零

时间:2013-05-27 20:10:09

标签: ruby null

我想遵循一些规则来连接范围。它工作正常,直到我尝试循环。这是代码。

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

1 个答案:

答案 0 :(得分:4)

Range#+条件为false时,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

解?

停止制作单一循环并使用power of standard library。当您想通过手动跟踪/更新当前索引来迭代集合时,有100次中的99次 - 这是一个坏主意。当你是新人时 - 它是100的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