NullVoxPopuli
NullVoxPopuli

Reputation: 65183

Ruby: How do you have optional first arguments? but default trailing arguments?

I'd like to have a method that is similar to this:

def method_with_optional(..., user = current_user, account = current_account)
...

because, I don't want to have to pass in current_user, and current_account every time. but as long as a user object isn't passed, the user formal parameter shouldn't be over-ridden.

This way I could do the following

method_with_optional(params[:id])

or

 method_with_optional(params[:id], User.new)

Upvotes: 0

Views: 223

Answers (3)

CubaLibre
CubaLibre

Reputation: 1703

An alternative to default arguments would be to assign the variable in the body of the method and to provide the User, Account arguments as a part of the params hash. You can check to see if the params contains a User and/or Account and then do the needful:

user = params[:user] || current_user
account = params[:account] || account

EDIT: If you cannot add things to the Params hash before invoking the method, then I don't know what you can do other than re-order the formal parameters in the method signature :)

Upvotes: 0

Mario Uher
Mario Uher

Reputation: 12397

Sorry, at the moment there is no built-in support for named parameters, you have to wait for Ruby 2.0.

Upvotes: 0

Jeff Paquette
Jeff Paquette

Reputation: 7127

What you're looking for are named arguments, which is not supported in Ruby 1.8, but you may have some success with arguments.

Upvotes: 1

Related Questions