News for hackers. Stuff that matters.
Re:Weird Ruby: Nil Conversions by bobbyi on Saturday February 24, 2024 @01:22PM (#39493833)
It is if the object can't be meaningfully cast to the type. I'd expect to get an exception. That's why they exist.

For example, consider explicitly casting the string "abc" to an int. Python throws a ValueError. Ruby silently ignores the problem and gives 0. I consider the Ruby behavior to be a gotcha.

Re:Weird Ruby: Nil Conversions by vidarh on Saturday February 24, 2024 @01:58PM (#39494156)
If you want to "explicitly cast" to an Integer only when the string strictly represents an int in Ruby you shouldn't be calling to_i. The Ruby behaviour is only a gotcha of you don't know the proper way of doing this in Ruby.

If you want an Integer or an exception you would call Integer(). If you want an Integer or nil, you would call Integer.try_convert(). If you call to_i, you're explicitly asking for a best-effort conversion, and shouldn't be surprised that's what you get.