gpt4 book ai didi

ruby - Ruby 导入的方法总是私有(private)的吗?

转载 作者:数据小太阳 更新时间:2023-10-29 07:09:37 25 4
gpt4 key购买 nike

最好用一个例子来解释:

文件1.rb:

def foo
puts 123
end

文件2.rb:

class A
require 'file1'
end
A.new.foo

将给出错误“':调用了私有(private)方法'foo'”。

我可以通过执行 A.new.send("foo") 来解决这个问题,但是有没有办法公开导入的方法?

编辑:澄清一下,我没有混淆 include 和 require。另外,我不能使用正常包含的原因(正如许多人正确指出的那样)是因为这是元编程设置的一部分。我需要允许用户在运行时添加功能;例如,他可以说“run-this-app --include file1.rb”,应用程序的行为将根据他在 file1.rb 中编写的代码而有所不同。抱歉应该解释得更清楚。

编辑:阅读 Jorg 的回答后,我意识到我的代码没有完全按照预期运行,他完美地回答了我的(被误导的)问题。我正在尝试做一些更类似于 str=(entire file1.rb as string); A.class_exec(str).

最佳答案

在 Ruby 中这是一种糟糕的方法。尝试通过模块使用混合:

文件1.rb:

module IncludesFoo
def foo
puts 123
end
end

文件2.rb:

require 'file1.rb'

class A
include IncludesFoo
end

A.new.foo
# => 123

关于ruby - Ruby 导入的方法总是私有(private)的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8799704/

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