1
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?

5
  • 3
    Hmm, downvotes. Well, +1 from me. JVK gave an example, showed what he tried, and the desired output is obvious. Commented Oct 30, 2012 at 18:37
  • 1
    Don't understand the down votes, its a good question Commented Oct 30, 2012 at 18:42
  • @DigitalRoss I am a newbie and learning Ruby for few days now. And it seems few people think stackoverflow is not for newbie to ask question. Commented Oct 30, 2012 at 18:42
  • Thank you all to answer this foobar question for a ruby newbie :) Commented Oct 30, 2012 at 18:43
  • It was a perfectly good question, keep asking. :-) Commented Oct 30, 2012 at 18:47

4 Answers 4

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

Comments

1

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.

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.