Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Ruby's default parameter values not get assigned to nil arguments?

Tags:

ruby

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.

like image 648
Patrick Smith Avatar asked May 08 '12 20:05

Patrick Smith


1 Answers

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.

like image 105
Jeremy Avatar answered Sep 18 '22 02:09

Jeremy