即使提供了参数,也会评估默认参数表达式吗?

时间:2014-11-27 01:43:27

标签: ruby

我已经读过在Ruby中,每个函数调用都会计算默认参数表达式。但是,如果我有这样的功能:

def foo(bar=super_heavy_work())
  # ...
end

并称之为:

foo "default argument not needed"

我现在提供了一个函数参数,所以我的问题是:在这种情况下调用超重函数函数,还是因为默认值不需要而被跳过?

1 个答案:

答案 0 :(得分:2)

不,如果传递参数,则默认值表达式评估:

def foo
  puts 'called foo!'
end

def bar(n = foo)
  puts 'called bar!'
end

bar
# => called foo!
# => called bar!

bar("some value")
# => called bar!

关键字参数也是如此:

def foo
  puts 'called foo!'
end

def bar(n: foo)
  puts 'called bar!'
end

bar
# => called foo!
# => called bar!

bar(n: "some value")
# => called bar!