0

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.

1

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

That's right. Otherwise you set instance variable of Poligon object.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.