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?
def foo(arg1, arg2 = (arg2_not_passed = true; "bar"))
puts arg1
puts arg2
puts 'arg2 was passed' unless arg2_not_passed
end
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With