Created
November 23, 2011 17:55
-
-
Save dcarley/1389365 to your computer and use it in GitHub Desktop.
Ruby string/integer typing rage.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# The principle of moderate-to-infuriating surprise. | |
irb(main):001:0> "23".to_i | |
=> 23 | |
irb(main):002:0> "23foobar".to_i | |
=> 23 | |
irb(main):003:0> "foo23bar".to_i | |
=> 0 | |
irb(main):004:0> "".to_i | |
=> 0 | |
# The only safe way. With thanks to @eazynow | |
irb(main):001:0> begin | |
irb(main):002:1* Integer("23foobar") | |
irb(main):003:1> rescue ArgumentError | |
irb(main):004:1> "yey" | |
irb(main):005:1> end | |
=> "yey" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Integer("23foobar") rescue nil