Search code examples
rubyclassmethodsinitializationzero

Class def method initialize to 0?


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

Solution

  • 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.