类方法及其表示法

本文详细介绍了类方法的三种定义方式:直接定义、使用关键字定义和使用类名定义,并解释了类方法的正确表示法。通过实例演示了每种定义方式的应用,帮助读者更好地理解和掌握类方法的定义和使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

类.方法

类::方法

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值