Avoid the usage of class (@@) variables due to their "nasty" behavior
in inheritance.
避免使用类变量(@@)因为他们讨厌的继承习惯(在子类中也可以修改父类的类变量)。
class Parent
@@class_var = 'parent'
def self.print_class_var
puts @@class_var
end
end
class Child < Parent
@@class_var = 'child'
end
Parent.print_class_var # => will print "child"
正如上例看到的, 所有的子类共享类变量, 并且可以直接修改类变量,此时使用类实例变量是更好的主意.
根据方法的用途为他们分配合适的可见度( private, protected ),不要让所有的方法都是 public (这是默认设定)。这是 Ruby 不是 Python。
public, protected, 和 private 等可见性关键字应该和其(指定)的方法具有相同的缩进。并且不同的可见性关键字之间留一个空格。
class SomeClass
def public_method
# ...
end
private
def private_method
# ...
end
def another_private_method
# ...
end
end
使用 def self.method 来定义单例方法. 当代码重构时, 这将使得代码更加容易因为类名是不重复的.
class TestClass
# bad
def TestClass.some_method
# body omitted
end
# good
def self.some_other_method
# body omitted
end
# Also possible and convenient when you
# have to define many singleton methods.
class << self
def first_method
# body omitted
end
def second_method_etc
# body omitted
end
end
end
class SingletonTest
def size
25
end
end
test1 = SingletonTest.new
test2 = SingletonTest.new
def test2.size
10
end
test1.size # => 25
test2.size # => 10
本例中,test1 與 test2 屬於同一類別,但 test2 具有重新定義的 size 方法,因此兩者的行為會不一樣。只給予單一物件的方法稱為单例方法 (singleton method)。










