Jul 02, 2022 | Ruby
Have you ever had a requirement to define a method where you don't really know how many arguments it will take? In Ruby, we can take advantage of something called splat operators.
Splat operators are very easy to use. The best to illustrate the simplicity is in an example.
Let's imagine that we have a method called my_method (yes, naming is hard, I know!) and this method will only take a number as argument.
So we would go and do something like this:
def my_method(variable)
variable
end
When we call this method and pass in a value, we will get that value returned. Simple.
Now, what happens if you want to extend this method and pass your first name as well?
Single plat operator has one mission only: convert all arguments into an array.
If we extend our my_method method (0.o), we can do something like this:
def my_method(*args)
args
end
And now when we call the my_method method like this:
my_method(35, "Marko")
We will get an array back:
[35, "Marko"]
Now a new requirement came in, and instead of arrays you want to be able pass a hash as argument.
To get this working, we can modify our method to look like this:
def my_method(**args)
args
end
And now we can use our method like this:
my_method(age: 35, name: 'Marko')
We get a hash back:
{ :age => 35, :name => 'Marko' }
We can COMBINE all of these and go crazy!
Here's an example:
def my_method(some_var, *some_arr, **some_json)
some_var, some_arr, some_json
end
my_method(17, 18, 19, 20, age: 35, name: 'Marko')
# => [17, [18, 19, 20], {:age=>35, :name=>"Marko"}]
And remember! Just because you can do something, doesn't mean that you should do it! 😂