# -*- coding: utf-8 -*-
# ruby定义类方法的三中形式
=begin
方法一: def 类名.方法名~end"
=end
class HelloWorld
def HelloWorld.hello(name)
print name, " said Hello."
end
end
jack = HelloWorld.hello("jack")
=begin
方法二: class << 类名~def 方法名~end end"
=end
class HelloWorld2
end
class << HelloWorld2
def hello(name)
print name, " said Hello2."
end
end
tony = HelloWorld2.hello("tony")
=begin
方法三: class 类名~def self.方法名~end end
=end
class HelloWorld3
def self.hello(name)
print name, " said Hello3."
end
end
cherry = HelloWorld3.hello("cherry")
ruby---类方法定义
最新推荐文章于 2026-01-08 11:47:31 发布
本文详细解释了在Ruby编程语言中定义类方法的三种常见方式,并通过实例展示了每种方法的具体应用。
111

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



