5 ms·
As others have mentioned, the safe navigation operator (&.) obviates the need for converting nil to "default" cast values. Would be nice if Integer(nil) worked
by block_dagger 3y ago
As others have mentioned, the safe navigation operator (&.) obviates the need for converting nil to "default" cast values. Would be nice if Integer(nil) worked like Array(nil) though.
- stinky613 3y ago> Would be nice if Integer(nil) worked like Array(nil) though. How would that work, though? A value of 0 is conceptually different from not having a value
- vidarh 3y agoI go back and forth on this. We "need" what Array() currently does. Arguably we need, and typically use it, far more than Integer(). I'd be inclined to argue both represent the most commonly desired (in Ruby anyway) treatment of input. Silently converting an integer is very often very bad, but being able to pass either single values or an array is often very good, and in the same cases guarding against nil is also very often desirable. At the same time it might be nice if they had names that were differentiated to indicate the behavioural difference, but I don't know what a better, similarly short option would be. We also do have "Integer.try_convert" and "Array.try_convert" which both consistently will refuse to convert "nil", though returning nil on failure instead of raising an exception, but I very rarely see it used.