JVK
JVK

Reputation: 3912

Ruby instance variable

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?

Upvotes: 1

Views: 82

Answers (4)

DigitalRoss
DigitalRoss

Reputation: 146221

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.

Upvotes: 1

pje
pje

Reputation: 22757

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

Upvotes: 4

Manjunath Manoharan
Manjunath Manoharan

Reputation: 4617

The attr_accessor, in short defines two methods.

def sides
end

def sides=
end

To get the value of the sides which have mentioned here, you need to init them in

def initialize
  @sides = 10
end

Upvotes: 1

Dave Isaacs
Dave Isaacs

Reputation: 4539

This exact question (even uses the same example code you have), is answered on railstips.org.

Upvotes: 1

Related Questions