Skip to content

Instantly share code, notes, and snippets.

@dcarley
Created November 23, 2011 17:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dcarley/1389365 to your computer and use it in GitHub Desktop.
Save dcarley/1389365 to your computer and use it in GitHub Desktop.
Ruby string/integer typing rage.
# 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"
@pvh
Copy link

pvh commented Nov 23, 2011

Integer("23foobar") rescue nil

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment