<< Previous Page
    

    
      Table of Contents
    

    
      Next Page >>
    
  
03
%q{Destructuring}
# Multiple variable assignment
a, b = [1,2]
a => 1
b => 2

a, b = [1,2,3,4,5,6]
a => 1
b => 2

# Hash in array
[1,2,3,a:5]
=> [1,2,3,{:a=>5}]

[1,2,3,a:5,b:7]
=> [1,2,3,{:a=>5, :b=>7}]

*a, b = [1,2,3,4,a:5]
a => [1,2,3,4]
b => {:a => 5}

*a, b = [1,2,3,4,a:5,b:7]
a => [1,2,3,4]
b => {:a => 5, :b => 7}

# Insert array with splat
a = [1,2,3,4,5]
[*a, 200]
=> [1,2,3,4,5,200]

a = [1,2,3,4,5]
[200, *a]
=> [200,1,2,3,4,5]

a = [1,2,3,4,5]
[200, *a, 100]
=> [200, 1, 2, 3, 4, 5, 100]

a = [1,2,3,4,5]
b = [60,70]
[200, *a, *b, 100]
=> [200, 1, 2, 3, 4, 5, 60, 70, 100]

a = [1,2,3,4,5]
b = [60,70]
[200, *a, 100, *b]
=> [200, 1, 2, 3, 4, 5, 100, 60, 70]

# Destructure hash with .to_a
b,c = {a: 5}.to_a
b => [:a, 5]
c => nil

(b,c) = {a: 5}.to_a
b => [:a, 5]
c => nil

((b,c)) = {a: 5}.to_a
b => :a
c => 5
# Cutting with splats
a, *b = [1,2,3,4,5,6]
a => 1
b => [2,3,4,5,6]

# note this is essentially the same as `b=[1,2,3,4,5,6]; a=b.shift`

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

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

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

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

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

# Adding hash with double splat
a = {b:9, c:10}
[1,2,3,a:5,**a]
=> [1,2,3,{:a=>5,:b=>9,:c=>10}]

# Only works at the end
a = {b:9, c:10}
[**a,1,2,3,a:5]
SyntaxError: unexpected ',', expecting =>

# Single splat hash add
a = {b:9, c:10}
[1,2,3,*a]
=> [1, 2, 3, [:b, 9], [:c, 10]]

# Double splat assignment
stuff = {a:5} stuff = {a:5}
{**stuff, b:4} {**stuff, a:2}
=> {a:5, b:4} => {a:2}

stuff = {a:5}
{**{c:6}, b:4} {a:2, **stuff}
=> {c:6, b:4} => {a:5}
03
    
      << Previous Page
    

    
      Table of Contents
    

    
      Next Page >>