mirror of
https://github.com/jbranchaud/til
synced 2026-01-07 00:58:02 +00:00
Add A Basic Case Statement as a Ruby til
This commit is contained in:
@@ -10,7 +10,7 @@ pairing with smart people at Hashrocket.
|
|||||||
|
|
||||||
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
|
For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud).
|
||||||
|
|
||||||
_1139 TILs and counting..._
|
_1140 TILs and counting..._
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -864,6 +864,7 @@ _1139 TILs and counting..._
|
|||||||
|
|
||||||
### Ruby
|
### Ruby
|
||||||
|
|
||||||
|
- [A Basic Case Statement](ruby/a-basic-case-statement.md)
|
||||||
- [A Shorthand For Rerunning Failed Tests With RSpec](ruby/a-shorthand-for-rerunning-failed-tests-with-rspec.md)
|
- [A Shorthand For Rerunning Failed Tests With RSpec](ruby/a-shorthand-for-rerunning-failed-tests-with-rspec.md)
|
||||||
- [Add Comments To Regex With Free-Spacing](ruby/add-comments-to-regex-with-free-spacing.md)
|
- [Add Comments To Regex With Free-Spacing](ruby/add-comments-to-regex-with-free-spacing.md)
|
||||||
- [Add Linux As A Bundler Platform](ruby/add-linux-as-a-bundler-platform.md)
|
- [Add Linux As A Bundler Platform](ruby/add-linux-as-a-bundler-platform.md)
|
||||||
|
|||||||
37
ruby/a-basic-case-statement.md
Normal file
37
ruby/a-basic-case-statement.md
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
# A Basic Case Statement
|
||||||
|
|
||||||
|
The syntax for case statements (or switch statements) is a little different for
|
||||||
|
each language. I often confuse the Ruby and JavaScript syntax or wonder if I
|
||||||
|
need to be using a colon anywhere.
|
||||||
|
|
||||||
|
Here is a demonstration of how to write a basic case statement in Ruby.
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
case ['taco', 'burrito', 'pizza', nil].sample
|
||||||
|
when 'taco'
|
||||||
|
puts 'Taco, eh. Carne asada or al pastor?'
|
||||||
|
when 'burrito'
|
||||||
|
puts 'Burrito, eh. Want it smothered?'
|
||||||
|
when 'pizza'
|
||||||
|
puts 'Pizza, eh. Cheese or pepperoni?'
|
||||||
|
else
|
||||||
|
puts 'What do you want to eat?'
|
||||||
|
end
|
||||||
|
```
|
||||||
|
|
||||||
|
This next example demonstrates two things. First, you can make things terser
|
||||||
|
with the `then` syntax. Second, the case statement does an implicit return of
|
||||||
|
whatever the last value is from the evaluated case. So it can be used as part
|
||||||
|
of a variable assignment.
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
question =
|
||||||
|
case ['taco', 'burrito', 'pizza', nil].sample
|
||||||
|
when 'taco' then 'Taco, eh. Carne asada or al pastor?'
|
||||||
|
when 'burrito' then 'Burrito, eh. Want it smothered?'
|
||||||
|
when 'pizza' then 'Pizza, eh. Cheese or pepperoni?'
|
||||||
|
else 'What do you want to eat?'
|
||||||
|
end
|
||||||
|
|
||||||
|
puts question
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user