Pattern Matching
Array Patterns
Array patterns destructure positions into named variables.
array pattern
An array pattern can match shape and assign elements to local variables.
Array Patterns
array_patterns.rb
Replay: real traced execution (multi-file project)
amount = 3
command = ["add", amount]
case command
in ["add", value]
result = value + 10
in ["remove", value]
result = 10 - value
else
result = 0
end
puts "command=#{command.join(",")}"
puts "result=#{result}"
amount = 1
command = ["add", amount]
case command
in ["add", value]
result = value + 10
in ["remove", value]
result = 10 - value
else
result = 0
end
puts "command=#{command.join(",")}"
puts "result=#{result}"
amount = 6
command = ["add", amount]
case command
in ["add", value]
result = value + 10
in ["remove", value]
result = 10 - value
else
result = 0
end
puts "command=#{command.join(",")}"
puts "result=#{result}"
amount ← 3, command ← ["add", 3]
1amount→ 3 = 3 #@amount=1, 62command→ ["add", 3] = ["add", amount3]34case command5in ["add", value]6 result = value + 107in ["remove", value]8 result = 10 - value9else10 result = 011end1213puts "command=#{command.join(",")add,3}"14puts "result=#{result13}"outputcommand=add,3 result=13
amount ← 1, command ← ["add", 1]
1amount→ 1 = 12command→ ["add", 1] = ["add", amount1]34case command5in ["add", value]6 result = value + 107in ["remove", value]8 result = 10 - value9else10 result = 011end1213puts "command=#{command.join(",")add,1}"14puts "result=#{result11}"outputcommand=add,1 result=11
amount ← 6, command ← ["add", 6]
1amount→ 6 = 62command→ ["add", 6] = ["add", amount6]34case command5in ["add", value]6 result = value + 107in ["remove", value]8 result = 10 - value9else10 result = 011end1213puts "command=#{command.join(",")add,6}"14puts "result=#{result16}"outputcommand=add,6 result=16