【问题标题】:Ruby: what is the best way to find out method type in method_missing?Ruby:在 method_missing 中找出方法类型的最佳方法是什么?
【发布时间】:2011-04-14 03:08:45
【问题描述】:

目前我有这个代码:

name, type = meth.to_s.match(/^(.+?)([=?]?)$/)[1..-1]

但这似乎不是最好的解决方案=\

任何想法如何使它变得更好? 谢谢。

【问题讨论】:

  • xyz= - 设置器,xyz? - 检查器,xyz - 吸气剂
  • 您能否在规范中更精确一点:== 方法或 === 方法的“类型”是什么?像Kernel#puts 这样的方法的“类型”是什么?
  • 您是否熟悉attr_reader 和类似的方法,这意味着您不必编写setter 或getter,除非它们具有复杂的逻辑?
  • 我知道类宏和 attr_* 系列,但此代码位于 method_missing 中,因此与 attr_* 无关

标签: ruby method-missing method-names


【解决方案1】:

最好的选择似乎是这样的: name, type = meth.to_s.split(/([?=])/)

【讨论】:

  • 方法“类型”并不真正存在,你是整个 ruby​​ 宇宙历史上唯一谈论它们的人 ;)
  • 我知道,只是不知道怎么形容,所以我认为“方法类型”会比“方法后缀”更好
  • 别听那个人的,他是个白痴。你在球上,他们通常被称为“Setters”和“Getters”。
【解决方案2】:

这就是我实现method_missing 的大致方式:

def method_missing(sym, *args, &block)
  name = sym.to_s
  if name =~ /^(.*)=$/
    # Setter method with name $1.
  elsif name =~ /^(.*)\?$/
    # Predicate method with name $1.
  elsif name =~ /^(.*)!$/
    # Dangerous method with name $1.
  else
    # Getter or regular method with name $1.
  end
end

或者这个版本,它只计算一个正则表达式:

def method_missing(sym, *args, &block)
  name = sym.to_s
  if name =~ /^(.*)([=?!])$/
    # Special method with name $1 and suffix $2.
  else
    # Getter or regular method with name.
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-21
    • 2015-05-10
    • 2013-03-31
    • 2018-08-11
    • 2012-01-09
    • 2015-08-08
    • 2012-04-28
    • 2011-05-26
    相关资源
    最近更新 更多