+ 12
What is **c in this following ruby code ?
def ques( a, *b , **c ) return a , b ,c end What is **c in.this this code and can anyone explain why is it good for use ?
4 Respuestas
+ 13
+ 6
Like the '*' splat operator captures an arbitrary number of arguments and returns an array; The '**' double splat operator captures keyword arguments and returns a hash.
code e.g:
def spt?(a, *b, **c)
p [a, b, c]
end
spt?(1, 2, 3, 'foo': 4)
--> [1, [2, 3], {:foo=>4}]
Check the below SO question and the article link for more info. It can be used when you want to pass arbitrary number of keyword arguments.
https://chriszetter.com/blog/2012/11/02/keyword-arguments-in-ruby-2-dot-0/
https://stackoverflow.com/questions/18289152/what-does-a-double-splat-operator-do
+ 3
That is a feature that was incorporated with Ruby 2.0.
When you work with Keyword arguments in your methods, you can have a little more flexibility. The two asterisks in this case serve to indicate that this argument is optional, and if you decide to use it, Ruby will store all the arguments that you provide within a Hash. A better way to illustrate this would be to do the following method:
def foo (a: 'a', b: 'b', ** args)
puts a
puts b
puts args
end
If you call the method with the following parameters: foo (a: 1, b: 2, c: 3, d: 4) the output will be the following:
1
2
{: c => 3,: d => 4}
There is a detail that perhaps is not easy to notice with my example: the name of the arguments must match the parameters, otherwise they will be stored inside the Hash. Consider the following case:
If you call the method with the following parameters foo (c: 1, d: 2, e: 3, f: 4) the output will be:
a
b
{: c => 1,: d => 2,: e => 3,: f => 4}
The method showed its default values for parameters a and b since I did not specify them when calling it. All other values were stored within the Hash.
PS: When you work with this type of arguments you can not use *args.