Skip to content

Instantly share code, notes, and snippets.

@jredville
Created September 7, 2012 16:51
Show Gist options
  • Save jredville/3667722 to your computer and use it in GitHub Desktop.
Save jredville/3667722 to your computer and use it in GitHub Desktop.
Ruby and Coffeescript destructured assignment
# more info at http://coffeescript.org/#destructuring
# Coffeescript also allows "pattern matching" style assignment
args =
column:
isBand: false
foo: 'bar'
row:
dataRowIndex: 1
foo: 'bar'
_cellIndex: 1
foo: 'bar'
{column:
isBand: band
row:
dataRowIndex: rowIndex
_cellIndex: cellIndex} = args
band #=> false
rowIndex #=> 1
cellIndex #=> 1
def Array.toy(size=10)
(1..size).to_a
end
arr = Array.toy #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# without a splat, only elements are assigned
head, second, rest = arr #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
head #=> 1
second #=> 2
rest #=> 3
# with a splat, the rest are put in the splatted var
head, second, *rest = arr #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
head #=> 1
second #=> 2
rest #=> [3, 4, 5, 6, 7, 8, 9, 10]
# splat can be on any arg
head, *mid, tail = arr #=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
head #=> 1
mid #=> [2, 3, 4, 5, 6, 7, 8, 9]
tail #=> 10
# extra elements get nil
first, second, third = [1,2] #=> [1, 2]
first #=> 1
second #=> 2
third #=> nil
# blocks also allow this (as do method calls)
{:a => [1,2], :b => [3,4]}.each do |k,v|
puts "k: #{k}"
puts "v: #{v}"
end #=> {:a=>[1, 2], :b=>[3, 4]}
# prints:
# k: a
# v: [1, 2]
# k: b
# v: [3, 4]
# destructuring value
{:a => [1,2], :b => [3,4]}.each do |k,(a,b)|
puts "k: #{k}"
puts "a: #{a}"
puts "b: #{b}"
end #=> {:a=>[1, 2], :b=>[3, 4]}
# prints:
# k: a
# a: 1
# b: 2
# k: b
# a: 3
# b: 4
# parallel assignment
a = 1 #=> 1
b = 2 #=> 2
a, b = b, a #=> [2, 1]
a #=> 2
b #=> 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment