class Polygon
attr_accessor :sides
@sides = 10
end
When I try to access
puts Polygon.new.sides # => nil
I get nil. How to access sides? What is wrong here?
class Polygon
attr_accessor :sides
@sides = 10
end
When I try to access
puts Polygon.new.sides # => nil
I get nil. How to access sides? What is wrong here?
Since ruby class definitions are just executable code, when you say @sides = 10 in the context of a class definition, you're defining that on Polygon (not instances of Polygon):
class Polygon
attr_accessor :sides
@sides = 10
end
Polygon.instance_variables
# => [:@sides]
You probably want to set the number of sides on the instances of Polygon, from the initializer:
class Polygon
attr_accessor :sides
def initialize(sides)
@sides = sides
end
end
Polygon.new(10).sides
# => 10
This exact question (even uses the same example code you have), is answered on railstips.org.
You need:
def initialize
@sides = 10
end
By assigning to @sides at the class level, you created a class instance variable rather than an instance variable of the object you created with #new.
In this case, you have an attribute of a given Polygon, but if it was actually an attribute of the class (like author or copyright or something) then you could reference it via the @whatever syntax if you were in a class method, created with def self.something ... end.