`
xitongyunwei
  • 浏览: 924909 次
文章分类
社区版块
存档分类
最新评论

类方法及其表示法

 
阅读更多

类方法有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的形式,我们总结为

类.方法

类::方法

两种方式,在实际程序中,采用其中任意一种即可。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics