Ruby:我需要帮助理解以下涉及 method_missing(method, *args, &block) 的代码

Ruby: I need help understanding the following code involving method_missing(method, *args, &block)

我在尝试了解如何创建您自己的 method_missing 方法时遇到了这段代码,但我不明白。 我不明白的是这些部分: method_sym[-1] == "=" 和 method_sym[0..-2] 他们指的是什么?我在 irb 中尝试了一些模拟,但这只是返回了一些奇怪的东西。

谁能帮我分解一下?我真的很感激。谢谢!

class UberHash
  def method_missing(method_sym, *args, &block)
    if method_sym[-1] == "="
      instance_variable_set("@#{method_sym[0..-2]}", args[0])
    else
      instance_variable_get("@#{method_sym}")
    end
  end
end

method_sym,即method_missing的第一个参数是代表方法名称的Symbol实例。因此,例如,如果您调用

a.foo

和Ruby找不到foo方法,将调用a.method_missing(:foo)

接下来,Symbol#[] 方法用于 return 符号的第 n 个字符或某些字符范围,如果您将 Range 传递给它。 -1 传入此方法表示 "last character"。 -2 表示 'the character before the last one' 等等 所以:

symbol = :foo
symbol[-1]
# => "o"
symbol[0..-2]
# => "fo"

args 表示传递给缺失方法的所有参数。所以,如果你调用你的方法:

a.foo(arg1, arg2, arg3)

argsmissing_method 中将是:

[arg1, arg2, arg3]

Ruby 中的方法可以在末尾使用 = 命名,这就是您创建 setter 方法的方式,例如:

class A
  def foo=(value)
    @foo = value
  end
end

这是常规方法,A.new.foo = some_value 只是一个语法糖,在底层,它等同于 A.new.foo=(some_value)。所以如果你打电话给

b.foo = 'value'

并且b.foo=未定义,Ruby将调用:

b.method_missing(:foo=, 'value')

因此 =method_sym[-1]