我想检查遇到的字符串类型:
class String
def is_i?
/\A[-+]?\d+\z/ === self
end
def is_path?
pn = Pathname.new(self)
pn.directory?
end
end
def check(key)
puts case key
when is_i?
puts "Could be a number"
when is_path?
puts "This is a path"
else
puts "Ok"
end
end
当我运行时check("1345425")
,出现以下错误:
undefined method `is_i?' for main:Object (NoMethodError)
我该怎么做才能纠正它?
您已经在String
实例上定义了函数,因此:
def check(key)
puts case
when key.is_i?
"Could be a number"
when key.is_path?
"This is a path"
else
"Ok"
end
end
或者
def check(key)
puts case key
when ->(s) { s.is_i? }
"Could be a number"
when ->(s) { s.is_path? }
"This is a path"
else
"Ok"
end
end
UPD请注意,我删除了对的不必要的后续调用puts
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句