Ruby methods sometimes need to distinguish an omitted argument from an explicit value, especially when `nil` and `false` are valid settings. A conventional optional argument defaulting to `nil` cannot tell those cases apart, and checking whether the value is `nil` still leaves omission indistinguishable from an explicit `nil`. One solution is to create a unique sentinel object and use it as the default, but that adds extra machinery.
A smaller Ruby technique uses an assignment inside the default argument expression, such as `value = (not_provided = true)`. Ruby evaluates that expression only when the caller omits the argument. In that case, the local flag becomes true, so the method can return the existing setting; when any value is supplied - including `false` or `nil` - the expression does not run, and the flag remains unset, so the method stores the supplied value. This lets one method cleanly handle reading and writing while preserving all possible values. The technique appears in Rails’ `index_with` implementation, where it distinguishes a call with no default from one that supplies a default value, while also supporting a block. The key idea is that Ruby’s evaluation of optional-argument defaults provides a compact way to make argument presence part of a method’s contract.
Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.