Ruby On Rails – Splat *

Today, we are going to discuss about Spalt. There are 2 areas to point out.

  • Splat Operator
  • Splat Expander

Spalt Operator (*)

This operator help to grouping collection of inputs to Array. See following example

def visited_countries(user, *countries)
  countries.each do |country|
    puts "This #{user} has visited #{country}"

visited_countries("Mark", "New Zealand", "Australis", "England", "USA", "Sweden"

Output will be,

This Mark has visited New Zealand
This Mark has visited Australis
This Mark has visited England
This Mark has visited USA
This Mark has visited Sweden

When you passing multiple parameters to visited_countries function, *countries argument grouping all the countries and presenting as a Array

We can use it for following purpose as well.

Let’s say all the user, countries and last visited date are included In one variable and then we can do,

countries_list = 'Mark Australia England USA Sweden 2020-12-12'
name, *countries, last = countries_list.split

puts 'user name: ' + name #=> Mark
puts 'countries: ' + countries.inspect #=> Australia England USA Sweden
puts 'last visited: ' + last #=> 2020-12-12

Splat Expander

This will help to turn values in to array and assign in to variable. Let’s try with example,

a, b, c, d, e, f, g, *z = *(1..10)

a => 1
b => 2
c => 3
d => 4
e => 5
f => 6
g => 7
z => [8, 9, 10]

Leave A Comment