Skip to content

Commit 09c4bb1

Browse files
committed
Add A Basic Case Statement as a Ruby til
1 parent a5c26c1 commit 09c4bb1

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
1010

1111
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
1212

13-
_1139 TILs and counting..._
13+
_1140 TILs and counting..._
1414

1515
---
1616

@@ -864,6 +864,7 @@ _1139 TILs and counting..._
864864

865865
### Ruby
866866

867+
- [A Basic Case Statement](ruby/a-basic-case-statement.md)
867868
- [A Shorthand For Rerunning Failed Tests With RSpec](ruby/a-shorthand-for-rerunning-failed-tests-with-rspec.md)
868869
- [Add Comments To Regex With Free-Spacing](ruby/add-comments-to-regex-with-free-spacing.md)
869870
- [Add Linux As A Bundler Platform](ruby/add-linux-as-a-bundler-platform.md)

ruby/a-basic-case-statement.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# A Basic Case Statement
2+
3+
The syntax for case statements (or switch statements) is a little different for
4+
each language. I often confuse the Ruby and JavaScript syntax or wonder if I
5+
need to be using a colon anywhere.
6+
7+
Here is a demonstration of how to write a basic case statement in Ruby.
8+
9+
```ruby
10+
case ['taco', 'burrito', 'pizza', nil].sample
11+
when 'taco'
12+
puts 'Taco, eh. Carne asada or al pastor?'
13+
when 'burrito'
14+
puts 'Burrito, eh. Want it smothered?'
15+
when 'pizza'
16+
puts 'Pizza, eh. Cheese or pepperoni?'
17+
else
18+
puts 'What do you want to eat?'
19+
end
20+
```
21+
22+
This next example demonstrates two things. First, you can make things terser
23+
with the `then` syntax. Second, the case statement does an implicit return of
24+
whatever the last value is from the evaluated case. So it can be used as part
25+
of a variable assignment.
26+
27+
```ruby
28+
question =
29+
case ['taco', 'burrito', 'pizza', nil].sample
30+
when 'taco' then 'Taco, eh. Carne asada or al pastor?'
31+
when 'burrito' then 'Burrito, eh. Want it smothered?'
32+
when 'pizza' then 'Pizza, eh. Cheese or pepperoni?'
33+
else 'What do you want to eat?'
34+
end
35+
36+
puts question
37+
```

0 commit comments

Comments
 (0)