Domanda

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
È stato utile?

Soluzione

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.

Altri suggerimenti

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
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top