Ruby 2.7 — Pattern Matching — First Impressions

The Short Version

Literal Matches

case 0
in 0 then true
else false
end
# => true

Multiple Matchers

case 0
in 0 | 1
true
end
# => true
case 0
in a | 0
end
# Error: illegal variable in alternative pattern

Captured Variables

case true
in a
a
end
# => true
case 0
in a if a == 0
true
end
# => true
case 0
in 0 => a
a == 0
end
case 0
in _ | _a
true
end

Destructuring

case [0, 1]
in a, a
a == 1
end
# => true
class C
class << self
attr_accessor :keys
end
def initialize(obj)
@obj = obj
end
def deconstruct
@obj
end
def deconstruct_keys(keys)
C.keys = keys
@obj
end
end
[[0, 1], C.new([0, 1])].all? do |i|
case i
in 0, 1
true
end
end
[[0], C.new([0])].all? do |i|
case i
in 0, 1
else
true
end
end
case []
in *a
a == []
end
case [0, 1, 2]
in *a, 1, 2
a == [0]
end
case 0
in *
true
end
case {a: 0}
in a: 0
true
end
case {}
in **a
a == {}
end

Triple Equals

case 'abc'
in /a/
true
end
case 0
in -> i { i == 0 }
true
end
case [0, 1, 2, 3, 4, 5]
in [0..1, 0...2, 0.., 0..., (...5), (..5)]
true
end
case object
in method_a: 0..10, method_b: String
true
end

Pin Operator

a = /a/
case 'abc'
in ^a
true
end
case [0, 0]
in a, ^a
a == 0
end

Thoughts?

--

--

--

Find new posts on dev.to: https://dev.to/baweaver

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Scrum methodology

The Ultimate List of Top Online Programming Courses

A software developer writing code

Making an Amazon Echo Skill, Part 2: Development

AWS Lambda + Serverless Framework + Python — A Step By Step Tutorial — Part 3 “Sending Emails from…

Maximum Subarray. Leetcode#Day3

CS 371p Spring 2021: Cindy Pham

I wrote an app to speed up my job hunting process.

On Feeling Stupid as an Early-Career Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Brandon Weaver

Brandon Weaver

Find new posts on dev.to: https://dev.to/baweaver

More from Medium

Hunting down spooky JSON module redefinition via Oj

Setting up Ruby on Rails with RVM, Puma, Mina, Nginx, Sidekiq and Redis on Amazon Linux 2

Seeding Data with Faker in Ruby

The logo for the Faker library

Better safe than sorry: use git hooks to avoid mistakes