Pattern Matching
Hash Patterns
Hash patterns match required keys and bind their values.
hash pattern
A hash pattern can require keys and assign their values to variables.
Hash Patterns
hash_patterns.rb
Replay: real traced execution (multi-file project)
kind = "click"
event = { kind: kind, x: 4, y: 7 }
case event
in { kind: "click", x: x, y: y }
summary = "click #{x},#{y}"
in { kind: "view" }
summary = "view event"
else
summary = "ignored"
end
puts "kind=#{kind}"
puts "summary=#{summary}"
kind = "view"
event = { kind: kind, x: 4, y: 7 }
case event
in { kind: "click", x: x, y: y }
summary = "click #{x},#{y}"
in { kind: "view" }
summary = "view event"
else
summary = "ignored"
end
puts "kind=#{kind}"
puts "summary=#{summary}"
kind = "skip"
event = { kind: kind, x: 4, y: 7 }
case event
in { kind: "click", x: x, y: y }
summary = "click #{x},#{y}"
in { kind: "view" }
summary = "view event"
else
summary = "ignored"
end
puts "kind=#{kind}"
puts "summary=#{summary}"
kind ← click, event ← {:kind=>"click", :x=>4, :y=>7}
1kind→ click = "click" #@kind="view", "skip"2event→ {:kind=>"click", :x=>4, :y=>7} = { kind: kindclick, x: 4, y: 7 }34case event5in { kind: "click", x: x, y: y }6 summary = "click #{x},#{y}"7in { kind: "view" }8 summary = "view event"9else10 summary = "ignored"11end1213puts "kind=#{kindclick}"14puts "summary=#{summaryclick 4,7}"outputkind=click summary=click 4,7
kind ← view, event ← {:kind=>"view", :x=>4, :y=>7}
1kind→ view = "view"2event→ {:kind=>"view", :x=>4, :y=>7} = { kind: kindview, x: 4, y: 7 }34case event5in { kind: "click", x: x, y: y }6 summary = "click #{x},#{y}"7in { kind: "view" }8 summary = "view event"9else10 summary = "ignored"11end1213puts "kind=#{kindview}"14puts "summary=#{summaryview event}"outputkind=view summary=view event
kind ← skip, event ← {:kind=>"skip", :x=>4, :y=>7}
1kind→ skip = "skip"2event→ {:kind=>"skip", :x=>4, :y=>7} = { kind: kindskip, x: 4, y: 7 }case event in { kind:
4case event{:kind=>"skip", :x=>4, :y=>7}5in { kind: "click", x: x, y: y }6 summary = "click #{x},#{y}"summary ← ignored
8 summary = "view event"9else10 summary→ ignored = "ignored"11endputs "kind=#{kind}"
13puts "kind=#{kindskip}"14puts "summary=#{summaryignored}"outputkind=skip summary=ignored