Thursday, 28 May 2020

Travels in Ruby part I

  • ruby
  • coding
  • travels-in-ruby

Today on my ruby travels, I realised that .to_i assumes a little too much:

"3a0a459e-7ca2-4648-ba80-dc6507f7d771".to_i
=> 3

As you can see, to_i has made some pretty wild assumptions about what it thinks you wanted, and has selected the first char from the string that is a valid integer.

It is always a good idea to make use of Integer() if you are uncertain. As you can see, wrapping the UUID in an Integer() check results in an ArgumentError being raised:

irb(main):003:0> Integer("3a0a459e-7ca2-4648-ba80-dc6507f7d771")
ArgumentError (invalid value for Integer(): "3a0a459e-7ca2-4648-ba80-dc6507f7d771")

Happy coding all!