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]
答案 0 :(得分:1)
在定义对象的属性(即它的length
)时,正确的方法是使用实例变量,而不是类变量。这是因为(在您的特定示例中),length
是特定square
的属性,而不适用于所有正方形。您的代码应如下所示:
class Square
def initialize(length = rand(20))
@length = length
end
def area
@length * @length
end
end
s1 = Square.new
puts s1.area
现在,我有点不清楚你打算通过使用那个类变量@@sqArray
来实现什么目的 - 但是例如,你可以使用这个商店列出所有已定义的Square
:< / p>
class Square
@@squares_list = []
def self.all_known
@@squares_list
end
def initialize(length = rand(20))
@length = length
@@squares_list << self
end
def area
@length * @length
end
end
这将允许您编写如下代码:
s1 = Square.new #=> #<Square:0x0000000132dbc8 @length=9>
s2 = Square.new(20) #=> #<Square:0x000000012a1038 @length=20>
s1.area #=> 81
s2.area #=> 400
Square.all_known #=> [#<Square:0x0000000132dbc8 @length=9>, #<Square:0x000000012a1038 @length=20>]
类变量有一些奇怪的行为和有限的用例;我一般建议你在开始学习Ruby时避免使用它们。请仔细阅读ruby style guide,了解有关最佳做法的一些常见惯例 - 包括变量/方法命名(使用snake_case
而非camelCase
或PascalCase
),空格等。< / p>