开发者

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:

  • I can't send 'a' with an empty string or nil.
  • I can't modify some_method.

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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜