diff --git a/README.md b/README.md index 5854e49..60ab97f 100644 --- a/README.md +++ b/README.md @@ -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). -_1139 TILs and counting..._ +_1140 TILs and counting..._ --- @@ -864,6 +864,7 @@ _1139 TILs and counting..._ ### 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) - [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) diff --git a/ruby/a-basic-case-statement.md b/ruby/a-basic-case-statement.md new file mode 100644 index 0000000..1650773 --- /dev/null +++ b/ruby/a-basic-case-statement.md @@ -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 +```