[#97678] [Ruby master Feature#16752] :private param for const_set — bughitgithub@...
Issue #16752 has been reported by bughit (bug hit).
5 messages
2020/04/02
[ruby-core:98092] [Ruby master Feature#13820] Add a nil coalescing operator
From:
sawadatsuyoshi@...
Date:
2020-04-30 09:00:59 UTC
List:
ruby-core #98092
Issue #13820 has been updated by sawa (Tsuyoshi Sawada).
Your proposal to distinguish `nil` from `false` is ad hoc, and is not a real solution for your use case, which is to add a value to a hash only when it does not yet have a corresponding key.
Following your way of doing it, you would still not be able to distinguish `opts1` that explicitly has a key-value pair `:foo` => `nil` and `opts2` that lacks such pair.
```ruby
opts1 = {foo: nil}
opts2 = {}
```
Particularly, applying your code to update `opts1` would overwrite the explicit `nil` value:
```ruby
opts1[:foo] ||= "foo"
```
Ruby is aware of such use case, and has already prepared a real solution: the `Hash#key?` method. The correct way of doing it is:
```ruby
opts1[:foo] = "foo" unless opts1.key?(:foo)
```
----------------------------------------
Feature #13820: Add a nil coalescing operator
https://bugs.ruby-lang.org/issues/13820#change-85328
* 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: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>