Jwan622 Jwan622 - 1 year ago 94
Ruby Question

Using (:send) in Ruby with keyword arguments?

I have a private method that I am trying to use #send to in Ruby to do some testing. The method is complicated and I don't want exposed outside of the class and so I want to test the method but I also don't need to list it as a public method. It has keyword arguments. How can I use

to call the method but also pass it keyword arguments/named parameters? Is there a way?

The method looks like this:

def some_method(keyword_arg1:, keyword_arg2:, keyword_arg3: nil)

Answer Source

Depends on how the keyword args are defined.

If they're defined inline for whatever reason, pass them inline:

SomeClass.send(:some_method, {keyword_arg1: 'foo', keyword_arg2: 'bar'})

If they're defined in a hash, you can unpack it instead:

hash = {keyword_arg1: 'baz', keyword_arg2: 'bing'}
SomeClass.send(:some_method, **hash)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download