suauha
Last Updated: February 25, 2016
·
516
· dperrymorrow
37b092a324da25d53fd63d780692b174

Ruby Gotcha with default params

So you have a method in Ruby that you want to have a default value for a param.

example:

my_method(param='default string')
  puts param
end

// calling the method
my_method()
// => default string

This works as expected, the omitted param defaults correctly. But what happens when you pass in the value of another variable which may or may not be nil?

strings = {headline: 'my headline', body: nil}
my_method strings[:body]

// => nil

What happened? I thought we set a default for the param? Well the default only works if the param was omitted, not if its falsely like I've assumed on a couple of occasions.

This comes into play when you are pulling dynamic values from objects to pass as params, and you do not know if the param you are passing is falsey or not.

Solution?

Default the param to nil, and then check for falsely.

example:

my_method(param=nil)
  param ||= 'default string'
  puts param
end

// calling the method
my_method()
// => default string
my_method nil
// => default string

So this solution covers both situations, the param is omitted, it still defaults to your string, and also if a nil value is passes as the parameter.

Say Thanks
Respond