Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using (:send) in Ruby with keyword arguments?

Tags:

ruby

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)

like image 543
Jwan622 Avatar asked Oct 13 '16 18:10

Jwan622


People also ask

How do you pass keyword arguments in Ruby?

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) .

How do you accept number of arguments in Ruby?

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.

How does * args work in Ruby?

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).

What is keyword parameter in Ruby?

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.


1 Answers

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)
like image 148
Makoto Avatar answered Sep 23 '22 02:09

Makoto