From: akim.demaille@... Date: 2020-10-01T08:41:35+00:00 Subject: [ruby-core:100249] [Ruby master Feature#13820] Add a nil coalescing operator Issue #13820 has been updated by akim (Akim Demaille). I second this proposal. Sure, it is not _needed_, we can always write things in a different way. As a matter of fact, with such an argument, hardly any improvement should be accepted. In practice when people use `||`, they do mean `??` (whatever its spelling). It just so happens that _most of the time_, it does what you want, because you happen to not be dealing with Booleans. But the semantics you mean to express is not about "truthness", but about "nilness". And occasionally you get bitten because `false` does exist, and behave differently. Wrt syntax, `??` chains much more naturally than conditionals. Many of the new languages make the difference, and support this explicitly. ---------------------------------------- Feature #13820: Add a nil coalescing operator https://bugs.ruby-lang.org/issues/13820#change-87836 * Author: williamn (William Newbery) * Status: Open * Priority: Normal ---------------------------------------- It would be nice if Ruby had an operator that only considered `nil` as false, like the null coalescing operators or "Logical Defined-Or operator" (Perl) found in some other languages. Ive seen things like `//` and `//=`m `??` and `??=`, or `?:` used for this. This would work like `||` and `||=` for short circuiting etc. except that only `nil` is considered a false condition. While Ruby considers only "false" and "nil" as false, with everything else true ("", [], {}, etc.) I still find occasionally people trip up when using logical or, `||` and `||=` when the value may be false. ```ruby a = 0 || 55 # = 0 Ruby already considers 0, "", etc. as true (oter languages do differ a lot here) a = 0 ?? 55 # = 0 So no change here a = nil || 55 # = 55, nil is false so right side is evaulated. a = nil ?? 55 # = 55, again no change a = false || 55 # = 55, however false is false for logical or a = false ?? 55 # = false, but its still a non-nil value ``` For example when doing things like: ```ruby def lazy @lazy ||= compute_this end def fetch(id, **opts) host = opts[:host] || default_host https = opts[:https] || true port = opts[:port] || (https ? 443 : 80) ... ``` Normally the intention is to use a default value or compute an action if no value is provided, which if the value may be false then requires special handling, or sometimes is missed and results in a bug. -- https://bugs.ruby-lang.org/ Unsubscribe: