我想检查我遇到的字符串类型:
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
的多余后续调用。
关于ruby - 如何在 Ruby 中为 String 类创建新函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33373869/