Introducing the Ruby Splat Operator
- Jared Swanson
- June 5, 2023
Ruby provides a powerful way to handle arguments and data structures with the use of splat (*
) and double splat (**
) operators. These are handy tools for developers looking to manipulate arrays and hashes in their methods.
Uses for the Single Splat Operator (*
)
Collecting Arguments
The single splat operator gathers all additional arguments provided to a method into an array.
def aboard_the_spaceship(*travelers)
puts "All aboard the spaceship! ๐"
travelers.each_with_index do |traveler, index|
puts "#{index+1}. #{traveler} is ready for the adventure! ๐"
end
end
aboard_the_spaceship('Alice', 'Bob', 'Charlie', 'Diana')
Output:
All aboard the spaceship! ๐
1. Alice is ready for the adventure! ๐
2. Bob is ready for the adventure! ๐
3. Charlie is ready for the adventure! ๐
4. Diana is ready for the adventure! ๐
Here, the single splat operator captures all arguments passed to the aboard_the_spaceship
method into the travelers
array.
With Other Arguments
The single splat can be used alongside regular arguments.
def mission_details(planet, *astronauts)
puts "Destination planet: #{planet}"
puts "Astronauts assigned to the mission: #{astronauts.join(', ')}"
end
mission_details('Mars', 'Alice', 'Bob', 'Charlie', 'Diana')
Output:
Destination planet: Mars
Astronauts assigned to the mission: Alice, Bob, Charlie, Diana
In this example, the splat operator in *astronauts
is used to โslurpโ up all of the astronaut names.
Array Destructuring
The single splat can be used to destructure arrays, breaking them down into individual variables.
main_planet, *junior_planets = ['Earth', 'Mars', 'Venus', 'Mercury']
puts "Main research planet: #{main_planet}"
puts "Junior research planets: #{junior_planets.join(', ')}"
Output:
Main research planet: Earth
Junior research planets: Mars, Venus, Mercury
The splat operator (*) is extracting all remaining elements of the array after the first element has been assigned to the main_planet variable. In this case, the main_planet variable is assigned the first element of the array (โEarthโ), while the remaining elements (โMarsโ, โVenusโ, โMercuryโ) are collected into a new array and assigned to the junior_planets variable.
This technique is particularly useful when you have an array with an unknown number of elements and you want to extract a specific subset of elements, or when you want to assign specific elements of an array to separate variables. It allows for more concise and readable code when compared to manually extracting each element from the array one by one.
The Double Splat Operator (**
)
This operator is all about hashes.
Merging Hashes
You can merge two hashes together using the double splat.
construction_stats = { built_in: '2020', construction_cost: '150 billion USD' }
current_stats = { current_crew: 6, operational: true }
space_station_stats = { **construction_stats, **current_stats }
puts space_station_stats
Output:
{:built_in=>"2020", :construction_cost=>"150 billion USD", :current_crew=>6, :operational=>true}
The double splat operator (**) is used for destructuring and merging hashes. In this example, two hashes (construction_stats and current_stats) are merged into a single hash (space_station_stats) using the double splat operator.
This technique allows you to combine multiple hashes into one, creating a new hash that contains all the key-value pairs from the original hashes. The code is more concise and readable compared to merging hashes manually or using other methods.
In Conclusion
Both the single splat and double splat operators in Ruby provide developers with increased flexibility when dealing with method arguments, arrays, and hashes. While they can streamline code and enhance readability, they also require a clear understanding to be used effectively. Use them wisely to tap into the full power of Ruby.