← Thu, Nov 5 digest

Moment of Ruby: An Argument for Nothing

read article ↗ hn thread ↗

A Ruby trick uses a default argument assignment expression to distinguish between an omitted argument and an explicit nil or false.

summary is enough The article explains a clever language idiom, but the comment thread provides necessary pushback on its practical utility.

summary

Ruby methods that double as getters and setters struggle to distinguish between an omitted argument and an explicit nil or false. While developers typically use a frozen sentinel object, Ruby evaluates default argument expressions only when omitted, allowing side-effect assignments as a detection flag. The author demonstrates this pattern using code adapted from Rails, but the technique sparks a debate on code readability and proper method design.

key points

  1. Ruby evaluates default argument expressions only when the argument is omitted, allowing side-effect assignments like value = (flag = true).
  2. This pattern enables methods to differentiate between an omitted argument and an explicit nil or false value.
  3. Alternative approaches include using a frozen sentinel object such as Object.new.freeze.

who should read it

Ruby developers interested in language idioms and metaprogramming tricks.

discussion mixed

consensus

Most participants find the trick clever, though opinions are sharply divided on whether such metaprogramming creates unreadable code.

pushback

Several participants argue that overloading a single method to act as both getter and setter is poor design regardless of the trick.

best comment by matharmin ↗

It's an interesting trick, but for a setter method you really need to use `def cloaking=(value)` instead of overloading the same method. It would help to give a more realistic example for where this technique can be useful.

It points out that a proper setter method avoids the underlying design problem entirely.

Generated by an LLM from the article and thread. Check the sources before relying on it.