类方法有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语言中定义类方法的三种方式:使用def类名.方法名~end、class<<类名~def方法名~endend及class类名~defself.方法名~endend。同时,文中还对比了类方法的不同表示方法。
2453

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



