开发者

How do I write this `method_missing`?

I have a开发者_如何转开发 class Wrapper that supports adding options that you can then look up later. It stores these options in an internal hash @dict.

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

How can I write a method_missing for Wrapper so that I can support nested calls on @dict?

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


If this isn't what you are looking for, leave a comment.

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜