Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Stop ignoring pattern matching!

Stop ignoring pattern matching!

Pattern matching was introduced as a major language feature in Ruby 2.7 and has been improved in subsequent releases, but not many people are using it yet. It’s really helpful and can make your programs clearer, simpler, safer, or all three. So why aren’t you using it? You should totally use it! I’ll show you how.

Given at Brighton Ruby 2022. A video is available at https://tomstu.art/stop-ignoring-pattern-matching.

Tom Stuart

June 30, 2022
Tweet

More Decks by Tom Stuart

Other Decks in Technology

Transcript

  1. It’s really helpful and it can make your code clearer,

    simpler & safer It’s really helpful and it can make your code clearer, simpler & safer
  2. Here is what I am about to say Not including

    this slide, that would take forever • Briefly: why bother? • OK OK, what’s pattern matching? • The basic bits • The intermediate bits • The advanced bits • Gotchas • The end
  3. https://docs.ruby-lang.org/en/3.1/syntax/pattern_matching_rdoc.html “Pattern matching is a feature allowing deep matching of

    structured values: checking the structure and binding the matched parts to local variables.”
  4. expression in pattern # returns true or false expression =>

    pattern # succeeds or raises as of Ruby 3.1.2
  5. case expression in pattern # … in pattern # …

    in pattern # … end # succeeds or raises as of Ruby 3.1.2
  6. Patterns: the advanced bits Please read the documentation, it’s good

    actually • Guard clauses • Variable and expression pinning • Array pattern coercion (#deconstruct) • Hash pattern coercion (#deconstruct_keys) https://docs.ruby-lang.org/en/3.1/syntax/pattern_matching_rdoc.html
  7. In summary then Big picture ideas you can remember •

    Ruby has pattern matching now • …and has done for years • it can make your code clearer, simpler and safer • …so it’s a huge shame to ignore it! • don’t be afraid of new Ruby features, and don’t shy away from trying stuff even if you don’t see other people doing it — someone has to go first
  8. In summary then Concrete things you can actually do •

    try converting “case when” to “case in” to get some easy benefits • look for opportunities to match the entire shapes of arrays and hashes instead of checking their elements individually • once you’re comfortable, dip a toe into more advanced features (guards, variable pinning, #deconstruct & #deconstruct_keys, find patterns) to get more power out of pattern matching • write a conference talk or a blog post and spread the word