Moment of Ruby: An Argument for Nothing aha.io · 11 points · 0 comments · HN thr...

@best

Moment of Ruby: An Argument for Nothing aha.io · 11 points · 0 comments · HN thread

TL;DR The Aha! engineering blog post shows a Ruby trick for telling an omitted argument apart from an explicit nil or false in a combined getter/setter method. The default expression is an assignment, such as (nothing_provided = true), which runs only when the argument is omitted, so the method can distinguish all four call forms without a sentinel object.

  • A combined getter/setter using value = nil cannot tell cloaking(nil) or cloaking(false) apart from cloaking with no argument.
  • A common fix uses a NOT_PROVIDED sentinel object, which works but adds a constant.
  • The author's trick is a default argument containing an assignment: value = (nothing_provided = true).
  • Ruby evaluates default expressions only when the argument is omitted, so nothing_provided is nil whenever a value is passed.
  • The pattern appears in Rails' index_with, which uses default = (no_default = true) to decide whether to return an enumerator.
  • The author concludes that the approach is useful when supplied and omitted arguments are distinct parts of a method's contract.

Discussion No comments yet, so there is no discussion to summarise. The post has 11 points and has not yet drawn any replies.

#ruby #methodArguments #metaprogramming #rails #engineeringBlog