gpt4 book ai didi

ruby - 我该如何写这个 `method_missing` ?

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

我有一个 Wrapper 类,它支持添加您可以稍后查找的选项。它将这些选项存储在内部散列 @dict 中。

w = Wrapper.new
w.foo # => NameError
w.foo = 10
w.foo # => 10

如何为 Wrapper 编写一个 method_missing 以便我可以支持对 @dict 的嵌套调用?

w = Wrapper.new
w.foo.bar.baz = 1000
w.foo.bar.baz # => 1000

最佳答案

如果这不是您要找的,请发表评论。

class Wrapper
def initialize(d={})
@dict = d
end

def method_missing(method, *args)
if method.to_s =~ /=$/
@dict[method.to_s.match(/^(.*)=$/)[1].to_sym] = args.first
else
@dict[method] ||= Wrapper.new
end
end
end

w = Wrapper.new
w.foo = 5
w.foo #=> 5
w.x.y.z = 32
w.x.y.w = 43
w.x.y.z #=> 32
w.x.y.w #=> 43

关于ruby - 我该如何写这个 `method_missing` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3073449/

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