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.
null?!nullis a proper value in any language I know that usesnull, just asnilis a proper value in Ruby.nilfor no value, overrides the default. If you want the default, omit the argument.