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 send
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)
So when you want to pass keyword arguments, you should always use foo(k: expr) or foo(**expr) . If you want to accept keyword arguments, in principle you should always use def foo(k: default) or def foo(k:) or def foo(**kwargs) .
Ruby has support for methods that accept any number of arguments, either positional or keyword. def some_method(*args) can be called with zero or more parameters. The args variable within the method will be an array of all values passed in when the method is called.
In the code you posted, *args simply indicates that the method accepts a variable number of arguments in an array called args . It could have been called anything you want (following the Ruby naming rules, of course).
Keyword Arguments (also called named parameters) are a feature of some programming languages, which gives the programmer the possibility to state the name of the parameter that is set in a function call. 02.04.2019.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With