开发者

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

开发者 https://www.devze.com 2023-03-16 12:07 出处:网络
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 a

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

精彩评论

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