【问题标题】:Using attribute in index array method to find index always returning nil in Ruby?在索引数组方法中使用属性来查找索引在Ruby中总是返回nil?
【发布时间】:2014-09-10 20:29:42
【问题描述】:

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

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

有人知道为什么会这样吗?

【问题讨论】:

  • color是什么类型?
  • 试试@chips.each{|chip| p chip.color},看看你会得到什么。
  • 该示例在使用“p”时有效。但是,它只是暂时解决了问题。我不需要输出,因为我搜索的数组比较大。
  • @chipsChip 类实例的数组。 color:white:red:green:black 类型的符号。
  • 我无法复制您的问题。它适用于我,使用包含 color 访问器的 Chip 类。

标签: ruby arrays loops variables ruby-2.1


【解决方案1】:

问题来了:

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

在另一个类的构造函数中,我写了一个与上面类似的 sn-p。它包含一个符号: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

感谢大家的帮助。进一步推动我深入代码有助于查明它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 2016-01-27
    • 1970-01-01
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    • 2022-12-29
    相关资源
    最近更新 更多