最佳答案
对于 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
有没有一种更简洁、更自然的 Ruby 方式来完成这种转换并检测字符串不是作为数字使用的?