测试string是否是Ruby on Rails中的数字 [英] Test if string is a number in Ruby on Rails
本文介绍了测试string是否是Ruby on Rails中的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的应用程序控制器中有以下内容:
I have the following in my application controller:
def is_number?(object)
true if Float(object) rescue false
end
以及我控制器中的以下情况:
and the following condition in my controller:
if mystring.is_number?
end
条件是抛出 undefined方法
错误。我猜我在错误的地方定义了 is_number
...?
The condition is throwing an undefined method
error. I'm guessing I've defined is_number
in the wrong place...?
推荐答案
创建 is_number?
方法。
创建辅助方法:
Create is_number?
Method.
Create a helper method:
def is_number? string
true if Float(string) rescue false
end
然后调用它是这样的:
my_string = '12.34'
is_number?( my_string )
# => true
Extend String
Class。
如果您希望能够直接在字符串上调用 is_number?
而不是将其作为辅助函数传递给辅助函数,那么你需要定义 is_number?
作为 String
类的扩展,如下所示:
Extend String
Class.
If you want to be able to call is_number?
directly on the string instead of passing it as a param to your helper function, then you need to define is_number?
as an extension of the String
class, like so:
class String
def is_number?
true if Float(self) rescue false
end
end
然后你可以用它来调用它:
And then you can call it with:
my_string.is_number?
# => true
这篇关于测试string是否是Ruby on Rails中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文