Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 14 / 68

The case/when Statement

In this lesson you will learn Ruby's case/when statement so you can express branching on a single value more clearly than a chain of if/elsif. This is for anyone searching for "Ruby case when how to use".

case / when is a tidier way to branch on a single value than lining up if / elsif clauses.

The sample code prints a day name based on day. It matches when 3, so "Wednesday" is printed, and else handles the case where nothing matched. Needing nothing like the break of other languages is characteristically simple Ruby.

A common stumbling block for beginners is trying to write break out of habit from another language's switch. Ruby's case never falls through into the next when, so no break is needed.

It keeps branches with many options readable and is a frequently used construct in practice. You can also omit then for an even more concise form - another Ruby touch.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)