Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
String#to_i当字符串不匹配任何数字字符时返回0,我理解包括我自己在内的许多人认为这不自然,并且希望nil在这种情况下返回。但马茨设计的不是这样。将实际上是"0"(或"00"等)的字符串与不包含数字字符的字符串区分开来的最佳方法是什么?
String#to_i
0
nil
"0"
"00"
采用:
Integer('') # => #<ArgumentError: invalid value for Integer: ""> Integer('0') # => 0
像这样的东西i = s.to_i ; i = nil if i == 0 && s != '0'。如果您经常需要它 - 要么使用monkeypatch to_i,要么添加better_to_i。
i = s.to_i ; i = nil if i == 0 && s != '0'