1

Consider this code:

class Polygon
  @sides=1
  @@sides = 10
  class << self; attr_accessor :sides end
  def self.sides
    @@sides
  end
end

If I print sides:

p Polygon.sides

I get 10. If I change the order of class and self.sides, I will get 1. What is the cause of this behaviour? How can I call the @@sides or @sides independently of the order of the methods?

edit

I found this excellent post that discuss the difference between class variables, class instance variables and instance variables.

1 Answer 1

0
class << self; attr_accessor :sides end

is equivalent to:

def self.sides
  @sides
end

def self.sides=(arg)
  @sides = arg
end

This sidesmethod then gets overwritten. Use two methods (with different names) to access both variables (or put them in an array and return that in a method).

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

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.