- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我有一个 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/
我正在尝试实现 method_missing 以将 $ 转换为其他货币,如 5.dollars yield 为 5、5.yen 将 yield 为 0.065 5.euro 6.56 等等。我现在可以
我有 Java 和 Ruby 背景,我想知道在 Erlang 中是否有任何等同于“method_missing”的东西。我查看了文档,我能看到的最接近的是使用 erl_eval 和 erl_parse
我正在尝试实现一个代码,在 method_missing 的帮助下,如果它符合某个关键字,它会自动创建一个方法。 到目前为止这有效: class Add def initialize()
我的程序中有一个团队类,我正在尝试使用 method_missing但是当该方法不存在时它没有运行该函数,而是给我一个错误:“团队的未定义方法‘hawks’(NoMethodError)” 我的代码如
我有一个 Wrapper 类,它支持添加您可以稍后查找的选项。它将这些选项存储在内部散列 @dict 中。 w = Wrapper.new w.foo # => NameError w.foo = 1
当我的 ruby 脚本失败时,我正在构建一种通过 mutt 向我发送电子邮件的方法。它看起来像这样: begin UnknownFunction() rescue subject
我正在尝试使用 method_missing 将美元转换为不同的货币。 class Numeric @@currency={"euro"=>2, "yen"=>6} def metho
我有以下 Ruby 方法,它给出了 RSpec 错误“堆栈级别太深”,我不确定为什么 - 非常感谢任何帮助! def method_missing(method_name, *args) full
在下面的代码中,roar 方法没有定义在 Lion 类中,但仍然可以使用 method_missing 调用。 class Lion def method_missing(name, *args)
我刚开始学习 Rails,我无法理解: 在我的 Post Controller 中,我没有显示方法(未描述),但我在我的 Controller 中放入了: def method_missing(nam
我是 Ruby 的新手,现在想了解一些关于元编程的知识。我想返回错过的方法名: class Numeric attr_accessor :method_name def method_miss
class Numeric @@currencies = {'yen' => 0.013, 'euro' => 1.292, 'rupee' => 0.019, 'dollar' => 1.0}
我知道 method_missing 是 Ruby 处理消息时的最后手段。我的理解是,它在对象层次结构中向上寻找与符号匹配的已声明方法,然后向下寻找最低的已声明method_missing。这比标准方
在方法定义中,有没有办法判断方法 method_missing 是被显式调用还是作为钩子(Hook)方法被调用? 使用方法initialize,可以通过执行以下操作来判断它是被显式调用还是作为钩子(H
我写了一个方便的 ActiveRecord 扩展来将方法委托(delegate)给一个基础对象(基于 multi-table inheritance) class ActiveRecord::Base
我有一个 ruby 程序,我想接受用户创建的方法,并使用该名称创建一个新方法。我试过这个: def method_missing(meth,*args,&block) name = meth.
我正在尝试编写一个通用模块,以将用于动态方法创建的 method_missing 模式应用于我的某些 Rails 模型。这些模型既有类方法也有实例方法。虽然我可以相当直接地为任一类案例编写模块:
类似于 Ruby 中的那个 最佳答案 是 ,从 Scala 2.9 开始,带有 -Xexperimental选项,可以使用 Dynamic特征 ( scaladoc )。扩展 Dynamic 的类获取
我一直在研究 powershell 的动态能力,我想知道一些事情 powershell 中是否有类似于 Ruby 的 method_missing() 的东西,您可以在其中设置“捕获所有方法”以动态处
我想为我的一个类定义一个 method_missing 函数,并且我希望能够传入一个散列作为参数列表而不是数组。像这样: MyClass::get_by_id {:id => id} MyClass:
我是一名优秀的程序员,十分优秀!