Making Decisions
7 min · Ruby
Run different code depending on whether something is true.
Enemy 1 of 5
if, else, and end
An if statement lets a program branch: it evaluates a condition and only runs the code that follows when that condition is true. In Ruby, there are no curly braces around the block — instead, the if runs everything until it hits a matching else (for the alternative path) or end (which closes the whole statement). Forgetting the end is one of the most common early Ruby syntax errors, since Ruby has no other way of knowing where the block stops.
Comparisons use the same operators you'd expect: > , < , >= , <= for ordering, and == for equality (note the double equals — a single = is assignment, and mixing them up is a classic bug in nearly every language that uses this convention, Ruby included).
Ruby is fairly indentation-friendly in convention (two spaces per level is the community standard) but, unlike Python, indentation is not what defines the block — the end keyword is what actually closes it. You could technically write everything on one line and it would still work, but consistent indentation makes nested logic vastly easier to read.
Loading editor...