gpt4 book ai didi

ruby - Ruby 的 using 方法有什么作用?

转载 作者:数据小太阳 更新时间:2023-10-29 08:04:28 26 4
gpt4 key购买 nike

元编程 Ruby 第 3 章的任务是编写与 C# 的 using statement 等效的 Ruby。 .我开始了:

class Resource
def dispose
@disposed = true
end
def disposed?
@disposed
end
end
def using(r)
puts "Not implemented."
end

r = Resource.new
using(r)

我还没有实现using。然而,当我运行这段代码时,我得到了

in `using': wrong argument type Resource (expected Module) (TypeError)

此外,如果我编写类似using(Kernel)using(Enumerable) 等的代码,程序将无误地完成。据我所知,Ruby 中没有 using 方法或关键字,但我在 pry 和 irb 中也有相同的行为。发生了什么事?

最佳答案

如果你想在 Ruby 2.1 中这样做,你需要修补 main 对象,因为它已经有了评论中提到的方法:

self.instance_eval do
def using(r)
puts "Not implemented."
end
end

关于ruby - Ruby 的 using 方法有什么作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20220631/

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