Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if optional arguments are passed in Ruby

If I have the following method in Ruby:

def foo(arg1, arg2 = "bar")
  puts arg1
  puts arg2
end

Is there a way of determining if a user passed a value in for arg2 within the method? Obviously I could just add if arg2 == "bar" to the method, but this doesn't catch the case where the user manually passed in "bar" herself. Of course, I could set the default to be something that no user would ever pass in, but then that gets pretty ugly pretty quickly.

Is there anything elegant out there?

like image 442
JacobEvelyn Avatar asked Oct 19 '13 23:10

JacobEvelyn


2 Answers

def foo(arg1, arg2 = (arg2_not_passed = true; "bar"))
  puts arg1
  puts arg2
  puts 'arg2 was passed' unless arg2_not_passed
end
like image 147
Jörg W Mittag Avatar answered Sep 29 '22 18:09

Jörg W Mittag


def foo(*args)
  case args.length
  when 1
    # arg2 was not given
    arg1, arg2 = args.first, "bar"
    ...
  when 2
    # arg2 was given
    arg1, arg2 = args
    ...
  else
    raise ArgumentError
  end
end
like image 33
sawa Avatar answered Sep 29 '22 17:09

sawa