【发布时间】:2019-09-13 12:01:06
【问题描述】:
定义一个用字符串初始化的类,例如如果方法 'abc?' 'abc' 将返回 true被称为。任何其他带有尾随“?”的方法将返回假。所有其他没有尾随“?”的方法将提出NoMethodError
【问题讨论】:
标签: ruby-on-rails ruby activesupport
定义一个用字符串初始化的类,例如如果方法 'abc?' 'abc' 将返回 true被称为。任何其他带有尾随“?”的方法将返回假。所有其他没有尾随“?”的方法将提出NoMethodError
【问题讨论】:
标签: ruby-on-rails ruby activesupport
您可以使用method_missing 来回复没有方法的消息。
在method_missing 中,我们可以检查方法名称,如果它以? 结尾,则检查它减去? 是否等于字符串(self)。
当使用method_missing 时,自定义还定义respond_to?。
class StringInquirer < String
private
def method_missing(method_name, *args, &block)
if method_name.to_s.end_with?('?')
self == method_name.to_s.delete('?')
else
super
end
end
def respond_to?(method_name, include_private = false)
method_name.to_s.ends_with('?') || super
end
end
name = StringInquirer.new('sally')
name.sally? # => true
注意这是区分大小写的。
name.Sally? # => false
【讨论】:
class NewStrInq < String
def initialize(val)
self.class.send(:define_method, "#{val}?") do
true
end
end
def method_missing(method)
method.to_s[-1] == '?' ? false : (raise NoMethodError)
end
end
【讨论】:
NewStrInq.new('abc'); NewStrInq.new('abcc').abc? # => true。如果你想这样做,你想在单例(又名幽灵)类上定义方法。
class StringInquirer < String
def initialize(str)
define_singleton_method(str + '?') { true }
super(str)
end
end
name = StringInquirer.new('sally')
name.sally? # => true
name.kim? # => NoMethodError
name.nil? # => false
通过为以问号结尾的所有方法提高NoMethodError,您将失去nil?等。
【讨论】: