splat (*) and double splat(**) arguments in ruby

Ruby is the flexibility it gives you to do the same thing in many different ways, so you can choose the way that suits you better. Deciding how you want your methods to receive arguments and therefore how those arguments are going to be passed is one of the things that you can perform in many different ways. We shall discuss how the splat(*) and double splat (**) argument passing works.

The most common way of passing arguments by using positional arguments as shown below

def something(a, b, c)
  [a, b, c]
end

something(7, 8, 9)
#=> [7, 8, 9]

But have you come across arguments with splat(*) and double splat(**) as shown below

def test(param, *args, **some)
  p param
  p args
  p some
end

Splat (*)

Splat(*) argument always accepts array as an argument, even if we pass many parameters in the method. It works as shown below.

def check_method(*args)
  p args
end

check_method(1, 2, 3, 4, 5)
=> [1 ,2 , 3, 4, 5]
def check_method(a, b, *args)
  p a
  p b
  p args
end

check_method(1, 2, 3, 4, 5)
=> 1
=> 2
=> [3, 4, 5]

check_method(1, 2)
=> 1
=> 2
=> []
def check_method(a, b, *args, c)
  p a
  p b
  p args
  p c
end

check_method(1, 2, 3, 4, 5)
=> 1
=> 2
=> [3, 4]
=> 5

Double splat(**)

Double Splat(**) argument always accepts hash_map as an argument, even if we pass many parameters in the method. It works as shown below.

def demo_method(**args)
  p args
end

demo_method
=> {}

Exception is thrown when a hash_map is not passed as a argument as shown below.

def demo_method(**args)
  p args
end

demo_method(1, 2)
ArgumentError: wrong number of arguments (2 for 0)
def demo_method(a, b, **args)
  p a
  p b
  p args
end

demo_method(2, 4, a: "qwe", b: "asd")
=> 2
=> 4
=> {:a=>"qwe", :b=>"asd"}

Let’s put all together now with default argument too.

def ruby_awesome(a, b, c = 0, *args, **some)
  p a
  p b
  p c
  p args
  p some
end

ruby_awesome(4, 5, 6, 7, 8, 9, 10, a: "qwe", b: "asd" )
=> 4
=> 5
=> 6
=> [7, 8, 9, 10]
=> {:a=>"qwe", :b=>"asd"}

4 Responses to “splat (*) and double splat(**) arguments in ruby

Leave a Reply

Your email address will not be published. Required fields are marked *