3

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

4

2 回答 2

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
于 2012-10-22T19:21:29.980 回答
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
于 2012-10-22T20:10:38.657 回答