I just finished reading the first few chapters of POODR. The author showcases a feature of attr_reader(accessor) which allows you to eliminate the need for the '@' when referencing instance variables after declaring them, in addition to the better known features of attr_.

However, with GuessingGame#solved? the code only works if I reference the most recent 'guess' using '@guess', not simply 'guess' as I was expecting. My inclination is that I have a method #guess as well and Ruby is thinking I am calling the method? Is this correct?

Any clarification would be much appreciated.

class GuessingGame
  attr_reader :answer
  attr_accessor :guess

  def initialize(answer)
    answer.is_a?(Integer) ? (@answer = answer) : (raise ArgumentError.new "You must enter an Integer.")
  end

  def guess(guess)
    @guess = guess
    if guess > answer
      :high
    elsif guess < answer
      :low
    else
      :correct
    end
  end

  def solved?
    @guess == answer
  end
end
有帮助吗?

解决方案

Your suspicion is correct.

The code:

attr_accessor :guess

is equivalent to:

def guess
  @guess
end

def guess=(new_value)
  @guess = new_value
end

That is, it creates a method which fetches the value of the instance variable and another method which sets the value of the instance variable.

When you redefine the method guess later, it overwrites the method defined implicitly by attr_accessor:

def guess
  3
end

def guess
  4
end

guess
#=> 4
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top