[ACCEPTED]-What does the * (asterisk) symbol do near a function argument and how to use that in others scenarios?-splat

Accepted answer
Score: 48

This is the splat operator, which comes 17 from ruby (and is thus not rails specific). It 16 can be applied in two ways depending on 15 where it is used:

  • to "pack" a number of arguments into an array
  • to split up an array into an argument list

In your function, you see 14 the splat operator used in the function 13 definition. The result is that the function 12 accepts any number of arguments. The complete 11 argument list will be put into args as an array.

def foo(*args)
  args.each_with_index{ |arg, i| puts "#{i+1}. #{arg}" }
end

foo("a", "b", "c")
# 1. a   <== this is the output
# 2. b
# 3. c

The 10 second variant would be when you consider 9 the following method:

def bar(a, b, c)
  a + b + c
end

It requires exactly 8 three arguments. You can now call this method 7 like follows

my_array = [1, 2, 3]
bar(*my_array)
# returns 6

The splat applied in this case 6 to the array will split it and pass each 5 element of the array as an individual parameter 4 to the method. You could do the same even 3 by calling foo:

foo(*my_array)
# 1. 1   <== this is the output
# 2. 2
# 3. 3

As you can see in your example 2 method, these rules do apply to block parameters 1 in the same way.

Score: 3

This is a splat argument, which basically 2 means that any 'extra' arguments passed 1 to the method will all be assigned to *args.

More Related questions