|
| 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