fivetwentysix
fivetwentysix

Reputation: 7487

How do set a default attribute value for a module class

Up until recently this use to work fine:

module Demo
  class << self
    attr_accessor_with_default :x, "hey"
  end
end

However that's no longer the case.

attr_accessor_with_default has been removed and I am left without a clue how to set this attribute a default value.

Upvotes: 4

Views: 3052

Answers (2)

thedanotto
thedanotto

Reputation: 7307

The following worked for me...

class Demo
  attr_accessor :x

  def initialize
    @x= "hey"
  end 
end

Then it can be called Demo.new.x => hey

Upvotes: 0

sepp2k
sepp2k

Reputation: 370172

For normal instance variables, you'd just set the variable to its default value inside initialize. For class instance variables, you can set it inside the class body:

module Demo
  class << self
    attr_accessor :x
  end

  @x = "hey"
end

Upvotes: 4

Related Questions