如何知道具有默认值的参数是否明确?

时间:2012-10-22 19:19:27

标签: ruby default

我有一个带有默认值的参数的方法。我需要知道值是来自用户还是默认值。用户也可以发送默认值。我怎么知道价值来自哪里?

2 个答案:

答案 0 :(得分:12)

你可以使用Nobu Nakada在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

答案 1 :(得分:4)

这也会起作用,看起来不那么难看:

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