3 ms·
> A place where we would use nil conversions is especially in logging and error handling — you can cast anything, including nil, to a string, and that is useful
by masklinn 3y ago
> A place where we would use nil conversions is especially in logging and error handling — you can cast anything, including nil, to a string, and that is useful in debugging.
Lots of languages can format anything to a string though. Even Java will let you write
"foo " + null
And logging / error handling / debugging seems like the context where you would least want nil to become an empty string (and thus be confusable with an actual empty string, or not appear in the output).
- epidemian 3y agoI agree with the grandparent general point, but i would say that it is string formatting more precisely where these nil conversions are useful. For example, you can write something like: bananas = 4 puts "you have #{bananas} banana#{'s' if bananas != 1}" And this works because: `if` is an expression, `if` evaluates to `nil` if the condition is not met and there's no `else`, and `nil.to_s` is an empty string. > And logging / error handling / debugging seems like the context where you would least want nil to become an empty string Yep, 100% agree. And i think Ruby's designers agree too, since the language has the shortest method possible, `p`, for print-debugging. You can do `p something` and that'll print a useful string for debugging (`""` for an empty string, `nil` for nil, `[]` for an empty array, etc).
- deleted 3y ago[deleted]
- vidarh 3y ago`"foo " + nil` is a TypeError in Ruby. You need to be explicit.
- masklinn 3y agoThank you for completely missing the point, your contribution is appreciated.
- vidarh 3y agoThe snark is completely unnecessary, and absolutely not appreciated. What is your point of that example, then? Absolutely nobody imagines any languages has no way of converting any value to a string. To me it came across as implying you were implying this was equivalent to what Ruby will do with the equivalent expression.