目前我已经有了这段代码:
name, type = meth.to_s.match(/^(.+?)([=?]?)$/)[1..-1]
但它似乎不是最好的解决方案= \
任何想法如何让它变得更好? 感谢。
答案 0 :(得分:1)
最好的选择似乎是:
name, type = meth.to_s.split(/([?=])/)
答案 1 :(得分:0)
这大致是我实现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