문제

I am trying to understand this code.

I am trying to initialize it to zero. def seconds=(), what does this mean?

I would have to call def seconds to get the variable. Isn't this the same if I would just put attr_accessor :seconds?

require 'time'
class Timer

  def seconds=(seconds)
    @second = seconds
  end

  def seconds
    @seconds
  end
end
도움이 되었습니까?

해결책

Yes, it's the same.

attr_accessor :seconds creates a setter and getter for the @seconds instance variable for you, so you don't have to do it explicitly.

Also, you misnamed @second in the setter.

다른 팁

To auto-initialize a class variable to zero, define it and then override its reader method:

class Timer
  attr_accessor :seconds

  def seconds
    @seconds ||= 0
  end
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top