在 Ruby on Rails 中测试字符串是否为数字 [英] Test if string is a number in Ruby on Rails

查看:14
本文介绍了在 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 method 错误.我猜我在错误的地方定义了 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

扩展 String 类.

如果您希望能够直接在字符串上调用 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

然后你可以调用它:

my_string.is_number?
# => true

这篇关于在 Ruby on Rails 中测试字符串是否为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆