Paul Miller
Paul Miller

Reputation: 89

How do I know whether an argument with default value got an explicit one?

I have a method with arguments that have a default value. I need to know if the value comes from the user or it is a default value. The user can send the default value too. How do I know where the values comes from?

Upvotes: 3

Views: 828

Answers (2)

ShadyKiller
ShadyKiller

Reputation: 710

This will also work and looks a little less ugly:

def my_method(a = implicit = 1)
  p a
  p implicit
end

# when calling without parameters then a = implicit = 1 is run, hence implicit is assigned a value 
> my_method
1
1

# when calling with a parameter then a = 1 statement is run. implicit will become nil here
> my_method 1 
1
nil

Upvotes: 4

user904990
user904990

Reputation:

You can use the trick proposed by Nobu Nakada back in 2004:

def some_method( a=(implicit_value=true; 1) )
    puts "a=#{a}; was set #{ implicit_value ? :im : :ex }plicitly"
end

> some_method
a=1; was set implicitly

> some_method 1
a=1; was set explicitly

> some_method 2
a=2; was set explicitly

Upvotes: 12

Related Questions