我在一个模块中有一个类,它有方法:
module D
class Dog
@name = 'pluto'
def setName( n )
@name = n
end
def getName ()
return @name
end
end
end
我是否可以在不创建getName
实例的情况下访问Dog
,就像C ++中的静态方法一样?类似的东西:
D::Dog.getName ()
而不是:
d = D::Dog.new
d.getName()
答案 0 :(得分:3)
我相信你正在寻找Ruby中所谓的类方法:
module SomeModule
class SomeClass
@class_variable = "some_string" # An instance variable on a class
def self.some_class_method
@class_variable # Return can be omitted in Ruby
end
# This is how setter methods are usually written in Ruby
def self.some_class_method= new_value
@class_variable = new_value
end
end
end
SomeModule::SomeClass.some_class_method
#=> "some_string"