0

String#to_i returns 0 when the string does not match any number characters, and I understand that many people including myself consider this unnatural and would rather expect nil to be returned in such case. But Matz designed it otherwise. What is the best way to distinguish strings that actually are "0" (or "00", etc.) from strings that do not include number characters?

sawa
  • 165,429
  • 45
  • 277
  • 381
  • 1
    You might want to check out this post: http://stackoverflow.com/questions/1235863/test-if-a-string-is-basically-an-integer-in-quotes-using-ruby – Mark Sep 22 '12 at 15:53

2 Answers2

4

Use:

Integer('')                         # =>  #<ArgumentError: invalid value for Integer: ""> 
Integer('0')                       # => 0  
xdazz
  • 158,678
  • 38
  • 247
  • 274
0

Something like this i = s.to_i ; i = nil if i == 0 && s != '0'. If you need it often - either monkeypatch to_i or just add better_to_i.

iced
  • 1,562
  • 8
  • 10