Robert K. wrote:
I do not see the connection of this to what I posted.
What I mean is, when you have an argument with a default value, you may
want to use the default value even when nil is explicitly passed in,
e.g. m(nil)
This is usually because the function is being called from a higher-level
function, which passes through a value from a higher level again, and
doesn’t want to be concerned with knowing what the default value is for
the low-level function. e.g.
Option 1 - not very DRY
def z(a = 123)
puts “Handling #{a}”
end
def y(count = 3, a = 123)
count.times { z(a) }
end
def x(count = 3, a = 123)
y(count, a)
end
x()
Option 2 - not always possible
def z(a = 123)
puts “Handling #{a}”
end
def y(count = 3, *args)
count.times { z(*args) }
end
def x(*args)
y(*args)
end
x()
Option 3 - not pretty
def z(a = 123)
puts “Handling #{a}”
end
def y(count = 3, a = nil)
count.times { a ? z(a) : z }
end
def x(count = nil, a = nil)
count ? (a ? y(count,a) : y(count)) : y
end
x()
Option 4
def z(a = nil)
a ||= 123
puts “Handling #{a}”
end
def y(count = nil, a = nil)
count ||= 3
count.times { z(a) }
end
def x(count = nil, a = nil)
y(count, a)
end
x()
This last option is the one which was called “silly”, but I think in
this case it’s actually quite a reasonable way to solve the problem. The
defaults are specified in exactly one place, and passing nil means ‘use
the default’
Regards,
Brian.