Re:Weird Ruby: Nil Conversions
by brink on Saturday February 24, 2024 @09:52AM
(#39491854)
I know companies that write banking software in this language. I wouldn't. But I guess if you write enough unit tests on the software and remember to avoid gotchas like this you'll probably be fine, and I think that's how they feel. To each their own, I guess.
[ Parent
| on HN ]
I really don't consider this to be a gotcha. If you explicitly cast to type X, it isn't surprising to get back an object of type X, right? These aren't implicit type conversions a la the Javascript + operator
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.
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.
What part / domain of "banking software" probably helps as well e.g. for a web frontend or other gateway to more resilient backends it might make sense enough.
Sometimes I do sort of wish there is a subset of Ruby that is more Pythonish. At least the Zen of it.
How do you feel about Crystal-lang?
I specifically avoid mentioning Crystal because there are a group of people on HN who doesn't like Crystal being mentioned in a Ruby Thread. But yes Crystal would be close if not "it".
Re:Weird Ruby: Nil Conversions
by drzaiusx11 on Saturday February 24, 2024 @07:02PM
(#39496274)
This is basically crystal is: a Ruby-like with inline type annotations like python3 and some of the "surprises" removed like Ruby's nil handling
Having worked in a handful of fintechs that use Ruby extensively, this generally isn't a problem in practice. In my experience there's a Money type that gets passed around rather than raw numbers, and that Money type will enforce a bunch of constraints, among them non-nilness.