[ruby-core:117067] [Ruby master Feature#20326] Add an `undefined` for use as a default argument.
From:
"shan (Shannon Skipper) via ruby-core" <ruby-core@...>
Date:
2024-03-06 17:32:41 UTC
List:
ruby-core #117067
Issue #20326 has been reported by shan (Shannon Skipper).
----------------------------------------
Feature #20326: Add an `undefined` for use as a default argument.
https://bugs.ruby-lang.org/issues/20326
* Author: shan (Shannon Skipper)
* Status: Open
----------------------------------------
Variations around `UNDEFINED = Object.new` are a fairly common pattern to see used as default arguments to distinguish between `nil` and no argument provided. For example, a Ruby implementation of Array#count might look something like:
``` ruby
class Array
UNDEFINED = Object.new
def UNDEFINED.inspect = 'UNDEFINED'
UNDEFINED.freeze
def count(item = UNDEFINED)
if item == UNDEFINED
# ...
end
end
end
```
I'd like to propose adding an `undefined` module function method on Kernel to remove the boilerplate for this fairly common use case. An `__undefined__` method or `__UNDEFINED__` keyword would be alternatives to `undefined`. An `undefined?` helper would also be an optional nicety:
``` ruby
class Array
def count(item = undefined)
if item.undefined?
# ...
end
end
end
```
A Ruby implementation might look like:
``` ruby
module Kernel
UNDEFINED = Object.new
def UNDEFINED.inspect = -'undefined'
UNDEFINED.freeze
private_constant :UNDEFINED
def undefined? = self == UNDEFINED
module_function
def undefined = UNDEFINED
end
```
--
https://bugs.ruby-lang.org/
______________________________________________
ruby-core mailing list -- ruby-core@ml.ruby-lang.org
To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org
ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/