Question

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
Was it helpful?

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.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top