gpt4 book ai didi

ruby - 默认情况下所有方法都是公开的吗?

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

如果我的主程序中有这个:

def hi
puts 'hi'
end
self.hi

它不会工作,因为 hi 是私有(private)的。

我了解到 Ruby 中的所有方法默认情况下都是公共(public)的,但事实并非如此,为什么?

最佳答案

main 环境中定义一个方法是很棘手的。当您在 main 中定义一个方法时,它默认是私有(private)的。所以你要么必须将它作为私有(private)使用:

def hi
puts 'hi'
end
hi

或明确公开:

def hi
puts 'hi'
end
public :hi
self.hi

关于ruby - 默认情况下所有方法都是公开的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19553843/

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