Daniel Rikowski
Daniel Rikowski

Reputation: 72514

Why are these default parameters defined as they are?

I'm currently learning Ruby and RoR and I stumbled across this declaration:

link_to_remote(name, options = {}, html_options = nil) 

I discovered that this pattern is used on several other Rails functions.

Why are the default values defined that way? Why not one of these two?

... options = {}, html_options = {}) 
... options = nil, html_options = nil) 

Is this some kind of convention I should follow in my own functions, too?

Upvotes: 2

Views: 130

Answers (2)

Chuck
Chuck

Reputation: 237060

The method is defined like this:

link_to_function(name, remote_function(options), html_options || options.delete(:html))

This allows you to specify the html_options as part of the options hash instead of as a separate parameter. On the other hand, the options hash is always passed to remote_function, so we need it.

It's also a bit more efficient to use the singleton nil rather than construct an array that will never be used every time the method is called. I wouldn't say this reason is so compelling that I wouldn't use {} if it made the resulting code cleaner, but in the absence of any other consideration, it seems like the logical thing to do.

Upvotes: 1

Wayne Molina
Wayne Molina

Reputation: 19586

Not an expert on it, but for options it might be because the calling code uses the merge method to combine whatever you pass in with the assumed defaults; setting it to nil would just remove all of the options. I'm not sure about html_options, but it might be something similar to that.

html_options might call a block and have something defined to check if it's given a hash or not. Like I said I'm not an expert but that might be why. I just checked on an Ubuntu VM and according to irb, an empty hash evaluates to true so that might be why. The calling code probably uses a block with something line:

if html_options
    # do stuff
end

so it's nil by default because the code would execute and probably give you a nil error with an empty Hash

Upvotes: 0

Related Questions