ruby - method_missing 中的 attr_accessor

标签 ruby metaprogramming

我是 Ruby 的新手,现在想了解一些关于元编程的知识。 我想返回错过的方法名:

class Numeric

  attr_accessor :method_name

  def method_missing(method_id)
    method_name = method_id.to_s
    self
  end

  def name
    method_name
  end

end

10.new_method.name #this should return new_method, but returns nil

最佳答案

在您的 method_missing 中,method_name 被解释为局部变量,而不是您所期望的 method_missing= 增变器方法。如果您显式添加接收器,那么您将得到您想要的:

def method_missing(method_id)
  self.method_name = method_id.to_s
  self
end

或者,您可以分配给 @method_name 实例变量:

def method_missing(method_id)
  @method_name = method_id.to_s
  self
end

attr_accessor 宏只是为你添加了两个方法,所以 attr_accessor :p 是这个的简写:

def p
    @p
end
def p=(v)
    @p = v
end

您可以在需要或需要时自由使用底层实例变量。

关于ruby - method_missing 中的 attr_accessor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9629634/

相关文章:

c++ - 使用 C++ 模板的数据映射器设计模式

c++ - SFINAE C++ 方法检查

python - Pro Django 这本书是否仍然相关?

ruby-on-rails - Ruby Gem 命令行工具

ruby - cucumber / capybara 错误:参数 [0] 未定义(Selenium::WebDriver::Error::JavascriptError)

我可以确定该类型是否是 C 中的指针类型吗?

julia - 如何在宏中将字符串转换为特定的枚举类型?

ruby-on-rails - 为什么这条评论会在 Ruby on Rails 上产生编译错误?

ruby-on-rails - rails 路线无法正确重定向

ruby-on-rails - 登录 delayed_job?