SEARCH

How-To Geek

Ruby If, Else If Command Syntax

The Ruby language has a very simple control structure that is easy to read and follow.

If syntax

if var == 10
print “Variable is 10″
end

If Else Syntax

if var == 10
print “Variable is 10″
else
print “Variable is something else”
end

If Else If Syntax

Here’s the key difference between Ruby and most other languages. Note that “else if” is actually spelled “elsif” without the e.

if var == 10
print “Variable is 10″
elsif var == “20″
print “Variable is 20″
else
print “Variable is something else”
end

Ternary (shortened if statement) Syntax

Ternary syntax is the same in Ruby as most languages. The following sample will print “The variable is 10″ if var is equal to 10. Otherwise it will print “The variable is Not 10″.

print “The variable is ” + (var == 10 ? “10″ : “Not 10″)

Lowell Heddings, better known online as the How-To Geek, spends all his free time bringing you fresh geekery on a daily basis. You can follow him on if you'd like.

  • Published 12/31/69

Comments (8)

  1. Analou Lamonon

    i can’t understand msdos command

  2. Analou Lamonon

    help me :(

  3. guilherme

    it isn’t msdos commands

  4. perl lover

    perl uses elsif.

    nothing is more natural.

    this is not a ‘key difference’ of ruby

  5. chris

    @perl lover: “more natural” != “most languages”

    “Here’s the key difference between Ruby and most other languages.” != “Here’s the key difference between Ruby and Perl Lover’s favourite language.”

    I do agree, it’s hardly a ‘key difference’! But citing a single counterexample does nothing to argue against this being a point of difference between Ruby and most other languages. Unless you invite people from most other languages to do same.

  6. Popy

    So people developped ruby to be able to spell “elsif” instead of “elseif” as other languages ?

  7. Florian

    In python there is elif. Is it the reason why Nasa uses it?

  8. Dude

    Ahhh you guys are all wrong.

    Its called elsif because its a magic secret!!!
    Just look out for the magic :3 MAGIC!!!!

Enter Your Email Here to Get Access for Free:

Go check your email!