Вопрос

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