开发者

Ruby: Pass options to method only if nonempty

开发者 https://www.devze.com 2023-02-15 21:10 出处:网络
I\'m given a hash self.options (possibly empty), and a method name.Now I need to call the method, passing in the options hash, like so:

I'm given a hash self.options (possibly empty), and a method name. Now I need to call the method, passing in the options hash, like so:

开发者_JAVA百科obj.send(method_name, ...args..., self.options)

But I'd like to support calling methods that don't expect an options hash at all. So if no options are given (self.options.empty?), I'd like to not pass an empty hash into the method. The best I could come up with is this:

obj.send(method_name, ...args..., *(self.options.empty? ? [] : [self.options]))

Is there a better idiom for this?


You don't need [] in case options is empty. *nil returns vacuity in that position.

Will this work?

obj.send(method_name, ...args..., *([self.options] unless self.options.empty?))

by the way, you can omit self, so you can have

obj.send(method_name, ...args..., *([options] unless options.empty?))


obj.send(method_name, ...args..., *([self.options.presence].compact))

or, how @sawa mentioned right, you can throw away self

obj.send(method_name, ...args..., *([options.presence].compact))
0

精彩评论

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