LuisVM
LuisVM

Reputation: 2793

Dynamically send a number of params to a method depending if parameters are nil or not

I want to avoid doing this:

if a
     some_method(a, b)
else
     some_method(b)
end

some_method is a function that accepts two parameters, first is a namespace, if not provided then it just accepts the method (b).

Notes:

Is there a way to do this in one single line?

Upvotes: 2

Views: 87

Answers (2)

user166390
user166390

Reputation:

Well, one way may be...

args = a ? [a, b] : [b]
some_method(*args)

So for the single line:

some_method(*(a ? [a, b] : [b]))

But is that really worth it? ^^

Happy coding.

Upvotes: 1

Senthess
Senthess

Reputation: 17580

It seems you have a method which allows a variable number of arguments. You could do it like this:

args = [a,b]
some_method(*(args.compact))

What this does: the compact removes nils from a list. Then the * ( splat operator ), "expands" the array elements into the proper positions.

Upvotes: 6

Related Questions