npresco
npresco

Reputation: 193

Optional argument syntax

I found this code under this question, which checks if any argument is passed to a method:

def foo(bar = (bar_set = true; :baz))
  if bar_set
    # optional argument was supplied
  end
end

What is the purpose of the ; :baz in this default value, and in what case would I use it?

Upvotes: 0

Views: 276

Answers (1)

ndnenkov
ndnenkov

Reputation: 36101

The idea is that = (bar_set = true; :baz) will be evaluated only if a value is not passed to the bar parameter.

In Ruby, the return value of multiple consecutive expressions is the value of the last expression. Hence = (bar_set = true; :baz) assigns the value true to bar_set, and then sets :baz as the value for bar (because the code in the parentheses will evaluate to :baz, it being the last expression).

If a parameter was passed, bar_set will be nil and the value of bar would be whatever was given.

Upvotes: 1

Related Questions