Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions




Ruby Programming
Previous Page Home Next Page

If and Unless Expressions

An if expression in Ruby is pretty similar to ``if'' statements in other languages.

if aSong.artist == "Gillespie" then
  handle = "Dizzy"
elsif aSong.artist == "Parker" then
  handle = "Bird"
  handle = "unknown"

If you lay out your if statements on multiple lines, you can leave off the then keyword.

if aSong.artist == "Gillespie"
  handle = "Dizzy"
elsif aSong.artist == "Parker"
  handle = "Bird"
  handle = "unknown"

However, if you lay your code out more tightly, the then keyword is necessary to separate the boolean expression from the following statements.

if aSong.artist == "Gillespie" then  handle = "Dizzy"
elsif aSong.artist == "Parker" then  handle = "Bird"
else  handle = "unknown"

You can have zero or more elsif clauses and an optional else clause.

As we've said before, if is an expression, not a statement---it returns a value. You don't have to use the value of an if expression, but it can come in handy.

handle = if aSong.artist == "Gillespie" then
         elsif aSong.artist == "Parker" then

Ruby also has a negated form of the if statement:

unless aSong.duration > 180 then
  cost = .25
  cost = .35

Finally, for the C fans out there, Ruby also supports the C-style conditional expression:

cost = aSong.duration > 180 ? .35 : .25

The conditional expression returns the value of either the expression before or the expression after the colon, depending on whether the boolean expression before the question mark evaluates to true or false. In this case, if the song duration is greater than 3 minutes, the expression returns .35. For shorter songs, it returns .25. Whatever the result, it is then assigned to cost.
Ruby Programming
Previous Page Home Next Page

  Published under the terms of the Open Publication License Design by Interspire