在Ruby中使用str.to_f时如何确定数值?

How to determine numeric value when using str.to_f in Ruby?

我试图找出数字字符串与任意字符串之间的区别:

'0'.to_f
#=> 0.0

'hello'.to_f
#=> 0.0

以上两个return一个Float。如果用户输入实际值 '0' 或用户输入值 'hello'

,我该如何捕捉差异

我正在尝试创建一个简单的摄氏度到华氏度计算器。如果用户输入 "hello" 程序应该输出 Please type in a number: 但如果用户输入 0 那么程序应该输出正确的华氏度计算。

您可以使用如下正则表达式:

/
\A   # anchor on start of a string, so there there is nothing more than float allowed
\-?  # optional minus
\d+  # non-empty row of digits
(
 \.  # dot
 \d+ # another row of digits
)?   # ? means both of the above are optional
\z   # anchor on end of a string, so there there is nothing more than float allowed
/x

单行版:/\A\-?\d+(\.\d+)?\z/

在典型的用例中,Float( ) 可能更好,但是使用正则表达式将您与 Ruby 的 Float 文字定义分开,如果您想要允许逗号作为小数点,或千位分隔符(Ruby 将分别只允许 ._)。正则表达式匹配也将只是 return truefalse,如果你想避免异常处理,这会很有用 - Float( ) 在失败时抛出的 ArgumentError 非常好泛型,因此它可能会被附近的其他方法调用抛出,因此可能难以正确处理,或者只会让您的代码变得丑陋。

使用这个:

number = Float( string_to_convert ) rescue nil
if number.nil? 
  puts "#{string_to_convert} is not a number"
else
  # DO the conversion
end

这将使用一组合理的规则将字符串值转换为浮点数,支持负数、科学记数法,同时不需要您编写正则表达式来尝试捕获在 Ruby.

需要 rescue 来捕捉转换失败的错误。


针对您的特定目的可能更好的 Ruby 代码(并将 Tamer 的回答的设计与 Stefan 在评论中的反馈相结合):

begin
  number = Float( string_to_convert )
rescue ArgumentError
  puts "'#{string_to_convert}' is not a number"
else
  # Do the conversion, using number variable
end

但是,如果程序流程比输入或破坏然后重复更复杂,我仍然发现单行代码很有用——当然前提是您稍后提出错误或可以处理丢失的问题值,因为转换为 Float 失败。

begin
  value = Float(input)
  # do your correct logic here
rescue ArgumentError
  puts "Please type in a number!"
end