类方法有3中定义的方式
(a)写成"def 类名.方法名~end"
class Hello
def Hello.hello(name)
print name,",hello."
end
end
Hello.hello("octopus") #=>octopus,hello.
(b)写成"class << 类名~def 方法名~end end"
class Hello
end
class << Hello
def hello(name)
print name,",hello."
end
end
Hello.hello("octopus") #=>octopus,hello.
(c)写成"class 类名~def self.方法名~end end"
class Hello
def self.hello(name)
print name,",hello."
end
end
Hello.hello("octopus") #=>octopus,hello.
------------------------------------------------------
方法的表示法
类名#方法名
这种写法一般限于文档或出于说明的目的,在程序中若采用这种方式,就会出现错误
在实际程序中,类方法的表示采用如Array.new或Array::new的形式,我们总结为
类.方法
类::方法
两种方式,在实际程序中,采用其中任意一种即可。
本文介绍了Ruby语言中定义类方法的三种方式:使用类名直接调用、利用类对象定义及通过self关键字定义,并展示了每种方式的具体语法及示例。
1809

被折叠的 条评论
为什么被折叠?



