31

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.

5
  • 3
    Which other language would use the default value if you give it null?! null is a proper value in any language I know that uses null, just as nil is a proper value in Ruby. Commented May 8, 2012 at 20:38
  • Passing a value to the function, any value, even nil for no value, overrides the default. If you want the default, omit the argument. Commented May 8, 2012 at 20:39
  • Yep, you're absolutely right. It's not that other languages treat it differently; it's that my mental models are screwed up and it's taking me a bit to get my head back into the code... Commented May 8, 2012 at 20:46
  • 2
    @MichaelBerkowski Yeah great, but if you do not have ruby 2, how would you "omit" only the second out of 3 parameters? Commented May 1, 2014 at 22:16
  • @NiklasB. C# does it like you mention and it makes passing arguments much easier. Commented Oct 23, 2017 at 20:20

3 Answers 3

73

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You can also use Ruby's splat operator (*) when calling that method:

dudes.each do |k,v| puts format_args(k,*v) end 

Output:

 larry......................... 60 moe........................... 1000 

Comments

0

In Ruby, methods always return something. Sometimes, there is nothing to return (query in database turns up empty or something like that). nil is for those cases; It means something like 'nothing here', but it is a reference to an object. To get the behaviour you want, just pass no parameter.

def talk(msg="Hello") puts msg end talk #=> "Hello" 

1 Comment

Or use nil as the default argument and do a msg ||= "Hello" inside the function.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.