Ruby Conditionals - Unless Statements
(Page 4 of 4 )
With IF statements, you are really seeking a True result from your Boolean question. With Unless statements, you are seeking just the opposite -- the False Boolean response.
Note that you cannot use elseif clauses in Unless statements.
hammer_time = 2
unless hammer_time == 2
puts “Ice Ice Baby!”
else
puts “Hammer Time!”
end
The above would result in: “Hammer Time!”
Case Statements
If you have a lot of If and elseif clauses, one way you can save time is by using the case statement. Here is an example:
action_type = “Flex”
case action
when “Walk”
puts “You are walking.”
when “Jog”
puts “You are jogging.”
when “Run”
puts “You are running”
when “Eat”
puts “Quit eating you fat pig!”
when “Flex”
puts “I didn't know muscles jiggled.”
else
puts “What? Sorry my hearing aid fell out, say it again.”
end
You could write If and else clauses for all of the above, but as you'll see it would constitute a lot more code. And let's face it, you're a lazy schlub.
action_type = “Flex”
if action_type == “Flex”
puts “I didn't know muscles jiggled.”
elseif action_type == “Walk”
puts “You are walking.”
elseif action_type == “Jog”
puts “You are Jogging.”
elseif action_type == “Run”
puts “You are running.”
else action_type == “Eat”
puts “Quit eating you fat pig!”
else
puts “What? Sorry my hearing aid fell out, say it again.”
end
As you can see, this can be time consuming. You can also use ranges within case statements. It looks like this:
yearly_salary = 40,000
case yearly_salary
when 0...10,000
puts “That's my monthly food bill.”
when 100,000...1,000,000
puts “I'm RIOTCH SNIOTCH!”
else
puts “Yeah, somewhere in that range.”
end
Well, we covered a lot of ground in that tutorial, but we still have more to cover. Be sure to come back next week, when I'll cover how to use Loops, how to call Methods, and maybe even how to not be so nerdy. Until then...
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |