Ruby switch statement (case-when)
mouse 250 · person cloud · link
Last update
2023-06-23
2023
06-23
« — »
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# any object that has a === method can be used in a when statement
id_odd = ->(x) { x % 2 == 0 }

case x
when 1..2 then puts 'is 1 or 2'
when ->(x) { x % 2 == 0 }
  puts 'is even'
when id_odd then puts 'is_odd'
when /[a-z]/ then puts 'chars'
when Car
  puts 'is a car'
else; ...
end

# with no case parameter => simplify if-elsif-...-end
case
when num > 10 ...
when num == 5 ...
end

# https://ruby-doc.org/3.2.0/syntax/pattern_matching_rdoc.html
cfg = {db: {user: 'admin', password: 'abc123'}}
case cfg
in db: {user:} # matches subhash and puts matched value in variable user
  puts "Connect with user '#{user}'"
in connection: {username: }
  puts "Connect with user '#{username}'"
else
  puts "Unrecognized structure of config"
end

Source: akshaykhot.com