Intro to Ruby - Conditionals

Overview
The following is a brief example of conditional logic in the Ruby language. Most of this should be familiar to you from other languages but convenience syntax like “unless” (opposite of “if”) might be new to you. As a rule of thumb, try not to use an “unless” with an “else” expression even though it would be syntactically correct. This is generally frowned upon and one should use the “if”, “else” expressions instead (much easier to read). Go ahead, study and play with the code yourself.
Code
class MerDeNoms
NAMES = ["Billy", "Charlie", "Merideth", "Dirk", "Sandra"]
def print_names
NAMES.each {|name| puts name}
end
def has_name? name
puts NAMES.include?(name) ? "#{name} is found." : "#{name} is not found."
end
def print_speciality name
puts "#{name} is not special." unless NAMES.include?(name)
end
def print_bio name
date = ""
if name == "Billy" then date = "1970"
elsif name == "Charlie" then date = "1950"
elsif name == "Merideth" then date = "1977"
elsif name == "Dirk" then date = "1990"
elsif name == "Sandra" then date = "2000"
else date = "?"
end
puts "#{name} was born in #{date}."
end
def print_status name
description = ""
case name
when "Billy" then description = "is sleeping."
when "Sandra" then description = "is hungry."
else description = "is day dreaming."
end
puts "#{name} #{description}"
end
end
names = MerDeNoms.new
# An example of the ternary operator.
puts "01 Ternary\n\n"
names.has_name? "Fred"
# An example of the "unless" statement. NOTE: You could also use the "if" statement in this manner as well.
puts "\n02 Unless\n\n"
names.print_speciality "Fred"
# An example of elsif logic.
puts "\n03 ElseIf \n\n"
names.print_bio "Dirk"
# An example of the case statement.
puts "\n04 Case \n\n"
names.print_status "Dirk"
Output
01 Ternary
Fred is not found.
02 Unless
Fred is not special.
03 ElseIf
Dirk was born in 1990.
04 Case
Dirk is day dreaming.
Download
The code above is provided as a Ruby script so that you can quickly execute all the examples above if you like. Just download, unzip, and type the following to execute all examples via the command line: ruby 11-conditionals.rb.
What’s Next
Loops
Article Series - Intro to Ruby
- Intro to Ruby - Getting Started
- Intro to Ruby - Strings
- Intro to Ruby - Numbers
- Intro to Ruby - Ranges
- Intro to Ruby - Arrays
- Intro to Ruby - Hashes
- Intro to Ruby - Variables and Scopes
- Intro to Ruby - Methods
- Intro to Ruby - Blocks
- Intro to Ruby - Classes
- Intro to Ruby - Modules
- Intro to Ruby - Conditionals
- Intro to Ruby - Loops
- Intro to Ruby - Exceptions
- Intro to Ruby - Testing
- Intro to Ruby - Next Steps
No comments yet.
Leave a comment
You must be logged in to post a comment.
Search
Categories
- Adventures
(105)
- Announcements
(36)
- Business
(19)
- Electronics
(28)
- Employment
(1)
- Epicurean
(10)
- Games
(3)
- Literature
(1)
- Mechanical
(4)
- Meetups
(18)
- Movies
(2)
- Music
(26)
- Photography
(1)
- Services
(29)
- Software
(136)