How to avoid repeating the same code depending if a method param is nil or not?

Hi everyone, I keep coming across this scenario where I have a method
that takes multiple parameters, most are optional. Within the method I
have either a call to another method, or I do something with the params.
It bothers me having to write the same call multiple times depending on
if a param is nil or not. Say the method I am calling must not take nil
param because it will assign a nil value (which is not desired).

What suggestions would you guys have for this?

These are my examples:
http://pastebin.com/56CSmztC

Got a solution. Before using the hash, I can call reject on it and
remove the nil items. As long as what ever I am calling does not want a
nil I can use do this.

Why is user state a parameter in multiple methods, and not an attribute
of the user?

These are just examples in attempt to try to explain my problem.

get_balance(user_id, user_state = nil)

What is the class or module which receives the get_balance() message, or
what is the class of the object which receives the get_balance()
message?

Say that a User has an Account that has a Balance, or some such.

user = User.new(user_id)

user.balance

user.balance(account: ‘savings’)

You may be encountering a hint that the design needs to be revisited and
perhaps revised.

Dala Streetz wrote in post #1169657:

Got a solution. Before using the hash, I can call reject on it and
remove the nil items. As long as what ever I am calling does not want a
nil I can use do this.

Why use reject? I’d prefer the opposite way:

get_balance(user_id, user_state = nil)
params = {:user_id => user_id}
params[:user_state] = user_state if user_state
Balance.get(params)
end

Cheers

robert

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs