DEV Community

Mbonu Blessing
Mbonu Blessing

Posted on

What I learned today(Ruby/Rails): Splat operator

Hello everyone

I have noticed recently that in my short journey as a Rails developer, there is still a lot I don't know about Ruby and Rails. I want to know more about them but the problem is just taking a course or reading a book won't help much if I don't practice. Plus I admitted that I can be overwhelmed with the loads of things things I need to learn and just prefer to sleep or watch a movie instead of learning. So I have decided to apply James Clear's advice from his book Atomic Habits and start small.

Introduction

Today, I will be talking about the splat(*) operator in ruby.

The splat operator is mostly used to define the arguments that can be passed to a method when you don't want to specify the number or arguments you want to pass or when you don't know the number of arguments you want to pass. It comes in 2 types, the single splat() and the double splat(*).

The single splat works as expected while the double splat takes key/values pairs as arguments.

Use cases

def splat_single(*numbers)
  puts "#{numbers}"
end

splat_single(1, 2, 3)

# => [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode
def splat_double(**numbers)
   puts "#{numbers}"
end

splat_double('a': 1, 'b': 2, 'c': 3)

# => {:a=>1, :b=>2, :c=>3}
Enter fullscreen mode Exit fullscreen mode

Resource/More reading
Everything you should know about Ruby Splats

Not related extras

Create a file with command line in Mac, simply run
touch <name_of_file>.<extension>

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.