开发者

Ruby: what is the best way to find out method type in method_missing?

开发者 https://www.devze.com 2023-01-16 21:44 出处:网络
At the moment I\'v开发者_StackOverflow中文版e got this code: name, type = meth.to_s.match(/^(.+?)([=?]?)$/)[1..-1]

At the moment I'v开发者_StackOverflow中文版e got this code:

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

But it doesn't seem to be the best solution =\

Any ideas how to make it better? Thanks.


The best option seems to be this: name, type = meth.to_s.split(/([?=])/)


This is roughly how I'd implement my 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

Or this version, which only evaluates one regular expression:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消