Search code examples
ruby

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


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.


Solution

  • 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.