Will Von Wizzlepig
Will Von Wizzlepig

Reputation: 73

References to object attributes from array values

I am working on solving a logic puzzle, and just want to compare clues to multiple instances of an object- checking attribute values to see if they are unknown (9), true (1), or false (0), then updating if needed.

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"] ]

In a binding pry, @one.color correctly returns the hash which I can easily check a clue against,

but in a nested set of loops over @produce and @attribs-

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

I get an error... the thing I hope to understand is how to assemble a working reference to the hash. I know I can store @array = [ @one.color ] and that works, but it does not make my logic engine work correctly.

Upvotes: 0

Views: 32

Answers (1)

Viktor
Viktor

Reputation: 2783

You probably want #public_send here:

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

Upvotes: 1

Related Questions