gpt4 book ai didi

ruby - 在 Ruby 中通过 using::operator 定义方法是什么意思?

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:56 24 4
gpt4 key购买 nike

例如:

class A
def A::f
end
end

什么是 A::f ?我想它既不是类方法也不是实例方法...

最佳答案

使用双冒号创建类方法。您可以通过做一个简单的测试来了解这一点:

class A 
def A::f
puts "Called A::f"
end
end

puts "A.public_methods:"
puts A.public_methods(false)
puts

a = A.new

puts "a.public_methods:"
puts a.public_methods(false)
puts

puts "Attempt to call f"
A.f
a.f

输出:

A.public_methods:
f
allocate
new
superclass

a.public_methods:

Attempt to call f
Called A::f
NoMethodError: undefined method ‘f’ for #<A:0x0000010084f020>

关于ruby - 在 Ruby 中通过 using::operator 定义方法是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4848679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com