Skip to content

Instantly share code, notes, and snippets.

@houhoulis
Last active April 30, 2018 23:43
Show Gist options
  • Save houhoulis/4713b139d3f861e893a3ab335f729d72 to your computer and use it in GitHub Desktop.
Save houhoulis/4713b139d3f861e893a3ab335f729d72 to your computer and use it in GitHub Desktop.
How define a method with a default argument of `nil` that can detect whether `nil` or no argument was passed in?

How define a method which takes an optional argument w/ a default value, but you have to distinguish whether the default arg or no arg was passed in?

class Foo
  def bar(a = "whatevs")
    # Was "whatevs" passed in, or no arg?
  end
end

Two very different examples that distinguish between nil and no arg:

class Foo
  def bar(a = (a_not_specified = true; nil))
    # [a_not_specified, a].detect &:present?
    puts "a is #{a}."
    puts "default value applied" if a_not_specified
  end
end

vs.

class Foo
  NOT_PROVIDED = Object.new

  def bar(a = NOT_PROVIDED)
    if a == NOT_PROVIDED
      puts "not provided"
      a = nil
    end
  end

  private_constant :NOT_PROVIDED
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment