Reputation: 59343
I have read that in Ruby, default argument expressions are evaluated for every function call. However, if I have a function like this:
def foo(bar=super_heavy_work())
# ...
end
And call it like this:
foo "default argument not needed"
I have now provided a function argument, so my question is: is the super heavy work function called in this case, or is it skipped since the default value isn't needed?
Upvotes: 4
Views: 722
Reputation: 12558
No, default value expressions are not evaluated if you pass an argument:
def foo
puts 'called foo!'
end
def bar(n = foo)
puts 'called bar!'
end
bar
# => called foo!
# => called bar!
bar("some value")
# => called bar!
The same goes for keyword arguments:
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!
Upvotes: 6