Programming Tutorials

if . . . elsif . . . else in Ruby on rails

By: Brian Marick in Ruby Tutorials on 2008-10-17  

Here is Ruby's if statement in all its glory, wrapped in a method:

Download if-facts/describe.rb
def describe(inhabitant)
if inhabitant == "sophie"
puts 'gender: female'
puts 'height: 145'
elsif inhabitant == "paul"
puts 'gender: male'
puts 'height: 145'
elsif inhabitant == "dawn"
puts 'gender: female'
puts 'height: 170'
elsif inhabitant == "brian"
puts 'gender: male'
puts 'height: 180'
else
puts 'species: Trachemys scripta elegans'
puts 'height: 6'
end
end

If given "paul", the method would work like this:

irb(main):001:0> load 'describe.rb'

=> true

rb(main):002:0> describe 'paul'

gender: male

height: 145

=> nil

The expressions on the if and elsif lines are called test expressions. Ruby test expressions executes each of them in turn until it finds one that's true. Then it executes the immediately following body (in this case, the lines that body use puts). If none of the test expressions is true, the body of the else is executed.

Just like everything else in Ruby, if returns a value. The value of a body is the value of its last statement (just as with method bodies), and the value of the entire if construct is the value of the selected body. So in the case of describe "paul", the value of the if is the value of puts "height: 145" (which happens to be nil).

You can leave out either or both of elsif and else. The if and end are required. If there's no else and none of the test expressions is true, the if "falls off the end," in which case its value is nil. Scripters often use if to pick which of several values is returned from a method. The following method returns a description of an inhabitant of my house:

Download if-facts/description.rb
def description_of(inhabitant)
if inhabitant == "sophie"
['gender: female' , 'height: 145' ]
elsif inhabitant == "paul"
['gender: male' , 'height: 145' ]
elsif inhabitant == "dawn"
['gender: female' , 'height: 170' ]
elsif inhabitant == "brian"
['gender: male' , 'height: 180' ]
else
['species: Trachemys scripta elegans' , 'height: 6' ]
end
end

I had the method return an array because puts prints each element of an array on a separate line:

irb(main):004:0> load 'description.rb'

=> true

irb(main):005:0> puts description_of('dawn')

gender: female

height: 170

=> nil






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in Ruby )

Latest Articles (in Ruby)