Ruby Programming Tutorial - Lesson 06 - Conditional Statements && logical decisions

in #ruby6 years ago

ruby.jpg

Conditional Statements

Human beings have this ability to compare different things and make decisions based upon what they think is best.
So lets say if I get an offer of 1500$/month job when I am empty pockets :p and if have to make a decision whether to take it or not... I have to compare many things before I make that decision ..
Most of the people would compare their empty pockets and see the package and take the job..

Similarly, our ruby programs need to make decisions, based upon comparisons between values.
then perform certain tasks.
for example

If balance of my account is greater than 5000 STEEM, power up 2500 STEEM

if we need to convert this English statement into a program that does exactly does this task.
we need to write some conditional statements or you can call them logical decisions in our ruby programs.

lets see how we make decisions in our ruby programs.
Lets write a simple conditional statement, which checks to see if my bank balance is less than a certain amount
based upon that decision it tells me if I am poor :D

bank_balance = 1000

if bank_balance <= 10000
    puts "You are Poor "
end

Conditional Statement comprises of the following things ..

  1. A conditional statement starts with a keyword "if" and ends with the keyword "end"
  2. After the keyword "if" we write our logical statement (logical statement returns true or false .. and it can be consisted upon comparison operators and logical operators)
  3. In between, we write all the tasks, we want this program to perform

Lets now write a Conditional statement, which has more tasks .. and its involves some arithmetic operations
Using all the skills we have learned so far, we can write programs like this fairly easily.

Note here, That we Started with an account balance, our program checked the balance, based upon
the amount, it made a decision to power up..
made arithmetic operations.. Displayed messages and completed the task..

Time to write some Fun Conditional Statements :)

This program decreases our sadness score and increases our happiness

We initially start with a high sadness score, and zero balance.
This program checks to see if our sadness score is greater than 500
then it reduces our sadness score by 500, increases our balance and makes us Happy :)

In this article you learned to make conditional statements

you also learned to make use of logical operator &&
you also learned to make use of comparison operators combined with logical operator