I'm new to Ruby and came across something that confused me a bit.
I set a default parameter value in a method signature.
When calling the method, I passed a nil
argument to that parameter.
But the default value wasn't assigned; it remained nil
.
# method with a default value of 1000 for parameter 'b' def format_args(a, b=1000) "\t #{a.ljust(30,'.')} #{b}" end # test hash dudes = {}; dudes["larry"] = 60 dudes["moe"] = nil # expecting default parameter value puts "Without nil check:" dudes.each do |k,v| puts format_args(k,v) end # forcing default parameter value puts "With nil check:" dudes.each do |k,v| if v puts format_args(k,v) else puts format_args(k) end end
Output:
Without nil check: larry......................... 60 moe........................... With nil check: larry......................... 60 moe........................... 1000
Is this expected behavior?
What ruby-foo am I missing?
Seems like nil
isn't the same "no value" that I'm accustomed to thinking of null
in other languages.
The default parameter is used when the parameter isn't provided.
If you provide it as nil
, then it will be nil
. So yes, this is expected behavior.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With