1

下面是一个基于数组元素实例属性的简单索引搜索:

chips = [Chip.new(:white), Chip.new(:black)]
color = :white
idx = chips.index { |chip| chip.color == color }

@chips无论数组中的值是什么,无论局部变量color设置为什么,这总是返回 nil 。color如果被替换为明确的符号,例如,这仍然适用:white,这是一个期望找到的示例索引。

这是类声明:

class Chip
   attr_reader :color, :value

   def initialize(color)
     @color = color

     case color
     when :white
      @value = 1
     when :red
      @value = 5
     when :green
      @value = 25
     when :black
      @value = 100
     end
   end
end

有谁知道为什么会这样?

4

1 回答 1

0

这是问题所在:

chips = [Chip.new(:white), Chip.new(:red), Chip.new(:green), Chip.new(:yellow)]

在另一个类的构造函数中,我写了一个与上面类似的片段。它包含一个符号,:yellow这是Chip课堂上使用的旧颜色。事实证明,这已被弃用。

稍后会有更多代码利用我试图开始工作的索引分配。但是,它一直返回,nil因为调用它的方法看起来像这样:

while some_val < another_val
  idx = nil
  color = nil

  if some_val >= SOME_CONST
   color = :black # This one did not exist in the array
  elsif some_val >= SOME_OTHER_CONST
   color = :green
  # ...

  idx = chips.index { |chip| chip.color == color }

  if idx.nil?
    return false
  end

  # ...
end

:yellow取而代之:black,使其不存在,因此创建了一个始终返回 nil 的案例,因为它永远无法找到。

我意识到,当我把我的例子放在这个问题上时,:white是任意的。我从来没有意识到我的测试代码是专门寻找:black.

感谢大家的帮助。让我更深入地了解代码有助于查明它。

于 2014-07-20T03:30:28.787 回答