Ruby Programming Tutorial - Lesson 08 - Case Statements

in ruby •  7 years ago 

ruby.jpg

In last article we learned about how can we write conditional statements, when we have multiple cases using IF - ELSIF
We also have an alternative to check multiple cases.

Lets take an example

Check for account balance IF it is 500, don't withdraw anything,  if it is 1000$ then withdraw 500
if its 2000, 5000, 10000 then keep only 1000 in account and withdraw the rest of balance.. 

Here is coding example ...


name        = "Bilal Haider"
balance     = 5000
age         = 27


case balance
when 500
  puts "Can't withdraw Balance is Low "
when 1000
  puts 'Withdraw 500$ from Account'
  balance = balance - 500
when 2000
  puts 'Withdraw 1000$ from account'
  balance = balance - 1000
when 5000
  puts 'Withdraw 4000$ from Account'
  balance = balance - 4000
when 10000
  puts 'Withdraw 9000$ from Account'
  balance = balance - 9000
else
  puts 'Only single-digit numbers are allowed'
end

## Check The balance after calculation are made

puts "You Now have balance of "
puts balance

This example helps you learn to use Case statements, See this image for results

Can you figure out what would be the result .. if We supplied initially a blance of 1500 ?

Not that this case statement, it will check the values which are exactly the numbers, written in cases.
e.g 500, 1000, 5000, 10000

It will not check for the value 1100, or 1001 .. or 1020 ..
Hence it will print the else part of the case... which is executed when no case exists, for the value supplied.

If you have a scenario where you need to check for different cases, This case statement will help you do it.
I am adding another example code in here..

Its used for grading .. for example you are making a software for a school. which needs to have a grading system.

Note that here we are using a slightly different version of case statement.. which returns the resulting value of the case. which we can store inside of variable "result" which we can use to display the output

score = 80

result = case score
   when 0..40 then "Fail"
   when 41..60 then "Pass"
   when 61..70 then "Pass with Merit"
   when 71..80 then "Pass with Distinction"
 when 81..100 then "You have Got an A Grade"
   else "Invalid Score"
end

puts result

Here is the output of the Program

Now that you have learned writing conditional statements you can write all the logic for your programs

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

Very useful :)

You got a 1.07% upvote from @postpromoter courtesy of @ronaldmcatee!

Want to promote your posts too? Check out the Steem Bot Tracker website for more info. If you would like to support the development of @postpromoter and the bot tracker please vote for @yabapmatt for witness!

This post has received gratitude of 1.95% from @appreciator courtesy of @ronaldmcatee!