Skip to main content

How to Use an if Statement in Ruby

· 6 min read
Jagdish Kumawat
Founder @ Dewiride

An if statement in Ruby runs its code only when a condition is true. elsif adds more conditions, checked in order, else runs when none of them was true, and end closes the statement.

Syntax​

Syntax
if <condition>
<code>
elsif <condition>
<code>
else
<code>
end
PartWhat it does
if <condition>Runs the code below it when the condition is true, and skips the rest.
elsif <condition>Optional, and you can have several. Checked only when every condition above it was false. It's spelled elsif.
elseOptional. Runs when no condition was true.
endCloses the statement. Every if needs its own.
<condition>Any expression. Only nil and false count as false; every other value, 0 and '' included, counts as true.

The Ruby documentation: "If the “test” expression evaluates to a true then the “then” expression is evaluated", and "An elsif executes when all tests above the elsif are false." For these tests, "nil and false are false-values and true and any other object are true-values".

The Example​

The example defines a method, check, that compares an order amount with a limit of 500 and prints whether the amount is over the limit, exactly at it, or under it. It calls the method with 900, 500 and 120, so each branch runs once. Then it leaves out the end that closes the if.

Prerequisites​

  • Ruby. This guide uses Ruby 4.0.10.

Step 1: Write the Code​

Create a file named main.rb:

main.rb, which defines a method check that sets limit to 500 and prints over the limit, exactly at the limit or under the limit with if, elsif and else, then calls it with 900, 500 and 120.

main.rb
def check(amount)
limit = 500
if amount > limit
puts 'over the limit'
elsif amount == limit
puts 'exactly at the limit'
else
puts 'under the limit'
end
end

check(900)
check(500)
check(120)

def check(amount) defines a method that takes the amount, and the last three lines call it. The if statement inside it has its own end, and the method has another.

Step 2: Run It​

Terminal
ruby main.rb
Output
over the limit
exactly at the limit
under the limit

The command is the same in zsh, bash and PowerShell.

Step 3: Leave Out an end​

Replace main.rb with a version whose if has no end of its own:

main.rb
def check(amount)
limit = 500
if amount > limit
puts 'over the limit'
elsif amount == limit
puts 'exactly at the limit'
else
puts 'under the limit'
end

check(900)
check(500)
check(120)
Terminal
ruby main.rb
Output
main.rb: --> main.rb

Unmatched keyword, missing `end' ?

> 1 def check(amount)
> 11 check(900)
> 12 check(500)
> 13 check(120)

main.rb:13: syntax errors found (SyntaxError)
> 1 | def check(amount)
| ^~~ expected an `end` to close the `def` statement
2 | limit = 500
3 | if amount > limit
~~~~~~
11 | check(900)
12 | check(500)
> 13 | check(120)
| ^ unexpected end-of-input, assuming it is closing the parent top level context

A zsh terminal where ruby main.rb prints over the limit, exactly at the limit and under the limit; for the changed file it prints Unmatched keyword, missing end, then syntax errors found (SyntaxError) with the lines it marks.

What Happened​

  • 900 is over 500, so the if branch ran.
  • 500 isn't over 500, so Ruby tried the elsif next, and 500 == 500 was true.
  • 120 matched neither condition, so the else branch ran.
  • Without its own end, the if took the method's end, which left the method open. Ruby stopped before running any of the file, with syntax errors found (SyntaxError): it expected an end to close the def statement, and the file ended first. Above that, Unmatched keyword, missing `end' ? listed the lines around the unclosed def.

Common Mistakes​

MistakeWhat happensDo this instead
Writing elseif instead of elsifRuby reads elseif as a method call inside the if branch: an amount of 500 printed nothing, and 900 printed over the limit and then stopped with undefined method 'elseif' for main (NoMethodError)Write elsif
Writing else ifThe second if needs its own end, so one end isn't enough: syntax errors found (SyntaxError)Write elsif
Writing = instead of == in a conditionif amount = 500 sets amount to 500, so the branch always runs. Ruby warned found '= literal' in conditional, should be ==Use == to compare
Expecting 0 or an empty string to count as falseBoth count as true: if 0 ran its branchCompare explicitly, as in count == 0 or name.empty?

Troubleshooting​

SymptomLikely causeFix
Unmatched keyword, missing `end' ? and syntax errors found (SyntaxError)An if, def or other block has no endAdd the missing end. The marked lines show where to look
undefined method 'elseif' for main (NoMethodError)elseif instead of elsifWrite elsif. Ruby itself suggested it: Did you mean? elsif
warning: found '= literal' in conditional, should be === instead of == in a conditionUse ==

FAQ​

Does an if return a value?​

Yes: the value of the branch that ran. The Ruby documentation: "The result value of an if expression is the last value executed in the expression." In my check, status = if amount > 500 with 'denied' in the if branch and 'allowed' in the else branch set status to "denied" for an amount of 900.

Can I write an if on one line?​

Yes, with then: if amount > 500 then puts 'over the limit' end. For a single statement, Ruby also has the modifier form, puts 'over the limit' if amount > 500. Both printed over the limit for an amount of 900.

Conclusion​

if, elsif and else pick one branch to run, checking the conditions from the top, and end closes the statement. Spell it elsif, compare with ==, and remember that only nil and false count as false.

Additional Resources​