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

Conditionals (if statements)

In this lesson you will learn how to write if statements in Ruby, and its readable brace-free conditional syntax. This is for anyone searching for "Ruby if statement syntax" or "Ruby elsif".

if / elsif / else / end handles conditional branching, and notably uses no braces. It helps to picture it as translating an everyday decision such as "if it is raining, take an umbrella" into code.

The sample code prints one of three messages depending on score using if / elsif / else. Notice the readable Ruby syntax where end marks the close instead of a brace.

A common stumbling block for beginners is forgetting end. Since there are no braces, end is mandatory and leaving it out is a syntax error. Writing elsif as one word rather than else if is another difference worth remembering.

Comparisons use operators such as >, <, and ==, and stacking more elsif clauses expresses three or more branches. This construct is the foundation of almost every Ruby program.

๐Ÿ“– 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)