如何在Ruby中为String类创建新函数?
我想检查遇到的字符串类型:如何在Ruby中为String类创建新函数?,ruby,Ruby,我想检查遇到的字符串类型: 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
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
当我运行检查(“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
或
UPD还请注意,我删除了对
put
的多余后续调用。您的检查方法没有在String类上定义,因此,当您编写时,是什么时候?你的路是什么时候?它试图在main上调用这些方法,因此出现了错误
您应该对字符串对象(键)调用以下方法:
...
when key.is_i?
...
when key.is_path?
...
你可以这样改变它
class String
def is_i?
/\A[-+]?\d+\z/ === self
end
def is_path?
pn = Pathname.new(self)
pn.directory?
end
end
def check(hash_key)
puts case hash_key
when Proc.new { hash_key.is_i? }
return "Could be a number"
when Proc.new { hash_key.is_path? }
return "This is a path"
else
return "Ok"
end
end
在
irb
中运行check('1312312')
,返回结果为“可能是一个数字”
您的检查方法未在String类上定义,但您正在调用的是is\i?在上面。试着在key.is_i时写作?什么时候key.is_path?相反,您在字符串上定义的方法很好。您的问题是您误解了case
的工作原理。请不要像这样在ruby中使用return
。
class String
def is_i?
/\A[-+]?\d+\z/ === self
end
def is_path?
pn = Pathname.new(self)
pn.directory?
end
end
def check(hash_key)
puts case hash_key
when Proc.new { hash_key.is_i? }
return "Could be a number"
when Proc.new { hash_key.is_path? }
return "This is a path"
else
return "Ok"
end
end