Ok i am not here to ask for an answer. But to be honest i am not really good in class variable. So i would appreciate you can guide me along with this piece of code.
I have read on class variable at those docs. I some what kind of understand it. But it comes to applying it for my own use. I would get confused.
class Square
@@sqArray = {}
#attr_accessor :length
def initialize
if defined?(@@length)
randno = "%s" % [rand(20)]
@@length = randno.to_i
@@sqArray = @@length
else
randno = "%s" % [rand(20)]
@@length = randno.to_i
@@sqArray = @@length
end
end
def Area
@@area = @@length * @@length
return @@area
@@sqArray[@@length.to_sym] = @@area
puts @@sqArray
end
end
s1 = Square.new
puts s1.Area
Let me explain this piece of code. Basically every time i create a Square object it would go to initialize method. A random number will be generated and pass it to @@length, and @@length will be assigned to hash @@sqArray as it's key. But now the problem is when i create a new object s1. When i want to display the Area i want to test out to print the hash @@sqArray with it's length as it's key and area as it's value. But now the problem is only returning it's area only. e.g 114 only. suppose to be e.g [ 24 => 114]