Pattern Matching
Find Pattern
A loop can use pattern matching to find the first record with a matching shape.
Find Pattern
find_pattern.rb
target =
records = [[:info, "ready"], [:warn, "hot"], [:done, "ok"]]
message = "none"
found = false
records.each do |record|
case record
in [kind, text]
if !found && kind == target
message = text
found = true
end
end
end
puts "target=#{target}"
puts "message=#{message}"
target =
records = [[:info, "ready"], [:warn, "hot"], [:done, "ok"]]
message = "none"
found = false
records.each do |record|
case record
in [kind, text]
if !found && kind == target
message = text
found = true
end
end
end
puts "target=#{target}"
puts "message=#{message}"
target =
records = [[:info, "ready"], [:warn, "hot"], [:done, "ok"]]
message = "none"
found = false
records.each do |record|
case record
in [kind, text]
if !found && kind == target
message = text
found = true
end
end
end
puts "target=#{target}"
puts "message=#{message}"
find pattern
Pattern matching inside a small loop can stop when the desired record appears.