Passing Missing Parameters

I saw a peculiar smell of code with default parameters. That is, when a method has a default value specified for one of its parameters, but the caller passes nil instead of passing any value. In most cases, this is because the caller has a hash and tries to pass a specific value from the hash. In particular:

 def foo(params) ... bar(params[:first], params[:second]) # :second doesn't exist end def bar(first, second = 2) end 

The second parameter, foo does not become the default, but becomes nil . The most common way I saw this is that the first line in the function line:

 second ||= 2 

Is there a better way to handle this? That is, whenever nil or no param is passed, assign a default value.

+4
source share
1 answer
 def bar(first, second = 2) 

This sets second to 2 if the argument is omitted. nil is a value with a value, so passing nil , because the value of the argument explicitly indicates that it is nil . This is special, so you can override the default value with nil if you want.

If you want your argument to assign a default value, if it is omitted, or nil , then ||= is the idiomatic way to do this.

 def bar(first, second = nil) second ||= 2 puts second end bar 1 #=> 2 bar 1, 3 #=> 3 bar 1, nil #=> 2 

second = nil allows you to skip the argument and sets the default value to nil . And if the argument is nil , you can set it by default. This means that passing to nil and omitting the argument is now essentially the same.

It does not behave so universally, because someday you will want to replace the default argument with nil . And the way you use the default arguments allows you to do just that.

+8
source

Source: https://habr.com/ru/post/1496263/


All Articles