ruby 严格将字符串转换为整数(或 nil)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24980295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:32:39  来源:igfitidea点击:

Strictly convert string to integer (or nil)

rubytype-conversion

提问by Alistair Cockburn

For web programming, numbers come in as strings. but to_iwill convert "5abc"to 5and "abc"to 0, both wrong answers. To catch these, I wrote:

对于 Web 编程,数字以字符串形式出现。但to_i将其转换"5abc"5"abc"0,这两个错误的答案。为了抓住这些,我写道:

def number_or_nil( s )
  number = s.to_i
  number = nil if (number.to_s != s)
  return number
end

Is there a neater, more Ruby-natural way of accomplishing this conversion and detecting that the string wasn't intended as a number?

是否有一种更简洁、更自然的 Ruby 方式来完成这种转换并检测字符串不是数字?

回答by Jim Gay

Use Integer(string)

使用整数(字符串)

It will raise an ArgumentError error if the string cannot convert to an integer.

如果字符串无法转换为整数,它将引发 ArgumentError 错误。

Integer('5abc') #=> ArgumentError: invalid value for Integer(): "5abc"
Integer('5') #=> 5

You'd still need your number_or_nil method if you want the behavior to be that nil is returned when a string cannot be converted.

如果您希望在无法转换字符串时返回 nil 的行为,您仍然需要 number_or_nil 方法。

def number_or_nil(string)
  Integer(string || '')
rescue ArgumentError
  nil
end

You should be careful to rescue from a particular exception. A bare rescue (such as "rescue nil") will rescue from any error which inherits from StandardError and may interfere with the execution of your program in ways you don't expect. Integer() will raise an ArgumentError, so specify that.

你应该小心地从一个特定的异常中拯救出来。一个简单的救援(例如“救援 nil”)将从任何继承自 StandardError 的错误中拯救出来,并且可能以您不期望的方式干扰您的程序的执行。Integer() 将引发 ArgumentError,因此请指定。

If you'd rather not deal with exceptions and just prefer a shorter version of your number_or_nil you can take advantage of implicit return values and write it as:

如果您不想处理异常而只想使用更短版本的 number_or_nil,您可以利用隐式返回值并将其写为:

def number_or_nil(string)
  num = string.to_i
  num if num.to_s == string
end

number_or_nil '5' #=> 5
number_or_nil '5abc' #=> nil

This will work the way you expect.

这将按照您期望的方式工作。

回答by hahcho

Use a simple regex to check stris an integer.

使用一个简单的正则表达式来检查str是一个整数。

def number_or_nil(str)
   str.to_i if str[/^-?\d+$/] and str.line.size == 1
end