从数组值引用对象属性

References to object attributes from array values

我正在解决一个逻辑难题,只想将线索与对象的多个实例进行比较 - 检查属性值以查看它们是未知 (9)、真 (1) 还是假 (0) ,然后根据需要进行更新。

class Fruit
  attr_number :number
  attr_accessor :color, :variety
  def initialize(number)
    @number = number
    @color = { "red" => 1, "brown" => 9, "green" => 9 }
    @variety = { "grape" => 9, "apple" => 9, "kiwi" => 0 }
  end
end

@one = Fruit.new(1)
@two = Fruit.new(2)
@produce = [ @one, @two ]
@attribs = [ :color, :variety ]
@clue = [ ["red", "apple"], ["green", "grape"] ]

在绑定撬中,@one.color 正确 returns 我可以轻松检查线索的散列,

但是在@produce 和@attribs 的一组嵌套循环中-

@produce.each do |food|
  @attribs.each do |describe|
    print food.describe
  end
end

我收到一个错误...我希望了解的是如何assemble 对散列的工作引用。我知道我可以存储 @array = [ @one.color ] 并且可以工作,但是它不能使我的逻辑引擎正常工作。

您可能需要 #public_send 此处:

@produce.each do |food|
  @attribs.each do |describe|
    print food.public_send(describe)
  end
end