Reputation: 4490
In this tiny class when the @sides=10
statement is executed?
How this statement is related to the initialize
method?
class Poligon
attr_accessor :sides
@sides=10
end
I am mostly used to Java where it is common to have inline initialization for the attributes. I am now trying to understand the complete initialization procedure for Ruby but I was not able to find it.
Upvotes: 0
Views: 3312
Reputation: 19228
Short answers:
The statemen @sides = 0
(which actually is an expression) is exectuted when the class
expression in evaluated.
It is not related at all with the initialize
method.
As you write it, the @sides
variable is a class instance variable, i.e. an instance variable of the Poligon
object (remember that in Ruby classes are objects of class Class
). You must initialize instance variables inside a method definitions (perhaps inside the initialize
method). Consider this example:
class Poligon
@class_sides = 'class instance variable'
def initialize
@instance_sides = 'instance variable'
end
end
Poligon.instance_variables
# => [:@class_sides]
Poligon.instance_variable_get(:@class_sides)
# => "class instance variable"
Poligon.new.instance_variables
# => [:@instance_sides]
Poligon.new.instance_variable_get(:@instance_sides)
# => "instance variable"
For more information about class instance variable and how they relate to class variables you can read this article by Martin Fowler.
Upvotes: 3
Reputation: 523
The initialize method is the constructor for the class. If you want, you can initialize your instance variables in the contructor:
class Poligon
attr_accessor :sides
def initialize(num_sides)
@sides = num_sides
end
end
But since @sides
is declared as an attr_accessor
, you can set/get it directly:
p = Poligon.new
p.sides = 10
Upvotes: 3
Reputation: 118271
You need to put this @sides=10
inside a method,with your current class definition.
class Poligon
attr_accessor :sides
def line
@sides=10
end
end
p = Poligon.new
p.line
puts p.sides
# >> 10
Upvotes: 3