gpt4 book ai didi

ruby - method_missing in "Programming Ruby"在我头上

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

方法缺失

*obj.method_missing( symbol h , args i ) → other_obj

Invoked by Ruby when obj is sent a message it cannot handle. symbol is the symbol for the method called, and args are any arguments that were passed to it. The example below creates a class Roman, which responds to methods with names consisting of roman numerals, returning the corresponding integer values. A more typical use of method_missing is to implement proxies, delegators, and forwarders.

class Roman
def roman_to_int(str)
# ...
end
def method_missing(method_id)
str = method_id.id2name
roman_to_int(str)
end
end
r = Roman.new
r.iv ! 4
r.xxiii ! 23
r.mm ! 2000

我刚听说 method-missing 并在 Programming Ruby 中了解更多信息 但是上面引用的书中的解释让我头疼。有没有人有更简单的解释?更具体地说,方法缺失仅由解释器使用,还是需要在程序中直接调用它(假设我只是在编写网络应用程序,而不是为 NASA 编写代码)?

最佳答案

最好不要认为 ruby​​ 有方法。当您调用 ruby​​“方法”时,您实际上是在向该实例(或类)发送一条消息,如果您已经为该消息定义了一个处理程序,它将用于处理并返回一个值。

所以 method_missing 是一个特殊的定义,每当 ruby​​ 找不到合适的处理程序时就会调用它。您也可以将其视为 * 方法。

关于ruby - method_missing in "Programming Ruby"在我头上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/715490/

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