
Issue #20326 has been updated by jeremyevans0 (Jeremy Evans). The problem with this is you could pass `undefined` just the same as `nil`. You would end up in a similar situation to JavaScript, which has both `null` and `undefined`. The correct way to handle this is by setting a local variable inside the default argument value: ```ruby class Array def count(item = (item_not_set = true)) if item_not_set # item argument was not passed else # item argument was passed end end end ``` Admittedly, this is a bit ugly, but the need to differentiate between passed default value and no supplied argument is fairly rare. Maybe there is a nicer way of supporting the same idea, that can still differentiate between passing the default value and not supplying an argument? ---------------------------------------- Feature #20326: Add an `undefined` for use as a default argument. https://bugs.ruby-lang.org/issues/20326#change-107141 * 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/