Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this parallel assignment with the splat operator work in Ruby?

Tags:

ruby

letters = ["a", "b", "c", "d", "e"]
first, *second = letters
first  # => "a"
second # => "["b", "c", "d", "e"]

I understand what this produces, but can't get my head around this. Is this basically Ruby magic? Can't think of any other programming language that would support this type of assignment with the splat operator.

like image 394
daremkd Avatar asked Mar 22 '23 20:03

daremkd


2 Answers

This is quite a common thing in functional languages, so Ruby is not alone. You have a list of items and want it separated in a head and a tail, so you can perform an operation on the first element of the list.

This also works:

letters = ["a", "b", "c", "d", "e"]
first, *middle, last = letters

In a functional language like Clojure, you would see something like:

(first '(1 2 3)) => 1
(rest '(1 2 3)) => (2 3)
like image 122
zwippie Avatar answered Apr 08 '23 12:04

zwippie


This is a very interesting thing here is described in great detail all the "magical properties"

for example

a, *b, c = [1, 2, 3, 4, 5]
a # => 1
b # => [2, 3, 4]
c # => 5

a, (b, c) = [2,[2,[6,7]]]
a
=> 2
b
=> 2
c
=> [6, 7]
like image 26
Philidor Avatar answered Apr 08 '23 13:04

Philidor