Modern Ruby: case/in
Since Ruby 3 there is, next to case/when, the more powerful pattern matching with case/in: it checks the shape of data and takes it apart in the same step. Perfect for our command array from the CLI lesson:
command = ["add", "ProjectX", 3.5]
case command
in ["add", project, hours]
"New entry: #{project} (#{hours}h)"
in ["report"]
"Generating report"
endThe pattern ["add", project, hours] only matches three-element arrays starting with "add" – and binds the remaining values to variables right away. Hashes deconstruct too, with type checks and a guard condition (if) on top:
entry = { project: "ProjectX", hours: 3.5 }
case entry
in { project: String => p, hours: Float => h } if h > 0
"#{p}: #{h}h - looks good"
in { hours: }
"Invalid hours: #{hours.inspect}"
endA pattern can also just say yes or no: value in pattern gives true or false – handy inside an if. With [*, "meeting", *], the find pattern, you look for an element anywhere in an array. And => takes a value apart without any case:
entry = { project: "ProjectX", hours: 3.5, tags: ["planning", "meeting"] }
if entry in { hours: Float => hours }
puts "#{hours} hours, as a Float"
end
puts "a meeting!" if entry in { tags: [*, "meeting", *] }
entry => { project:, tags: [first_tag, *] }
[project, first_tag]The rest of modern Ruby fits right in: endless methods for one-liners (def square(x) = x * x) and the hash shorthand { project:, hours: } when variable and key share a name.
dispatch(command) with case/in: ["add", project, hours] → "Entry: <project> (<hours>h)", ["report"] → "Report", ["export", format] → "Export as <format>", anything else (else) → "Unknown command".# def dispatch(command)
# case command
# in ...
# end
# end