Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 3

# 2.

0 Boolean Expressions in Ruby Beginner's Guide to Expressions in Ruby ======================================= Ruby uses the == operator for comparing two objects. Let us try a simple exercise: write an expression that checks whether the value of the variable name is "Bob": name == "Bob" The other usual operators like greater than (>), less than (<), greater than or equal to (>=) etc. are supported. The next exercise is to write an expression th at validates whether age is less than or equal to 35. age <= 35 # change this expression Boolean expressions like the above always return either the true or false object s. Combining Expressions using the && and || operators You can use the keywords || (read as 'or'), && (read as 'and') to combine expres sions. Try modifying the following expression to check whether age is greater th an or equal to 23 and the name is either Bob or Jill. age >= 23 && (name == 'Bob' || name == 'Jill') Just like the order of operations in mathematical expressions (PEMDAS anybody?), Ruby also has a set of laws governing the precedence of its various operators. However it is not something you need to be concerned about for now. Just make su re to use parentheses generously so that the order of operation is unambiguous t o Ruby as well as for someone reading your code. Negating expressions ==================== Ruby lets you negate expressions using the ! operator (read as 'not'). For insta nce, ! (name == 'Jill') will return false if the name is Jill and true for any o ther name. Now try writing a simple expression that accepts any name except Bob !(name == "Bob") Awesome! Now that you've learned the basics of writing boolean expressions in Ru by, let us see how we can use them to decide the flow of our application in the next lesson. # 2.1 The if..else construct Ruby Conditional Branching : the 'if' statement =============================================== You can use Ruby's Boolean Expressions to specifiy conditions using the usual if ..else construct. Let us take a look at a simple example: Example Code: def check_sign(number) if number > 0 "#{number} is positive"

else "#{number} is negative" end end When you run the above example, it will tell you that 0 is negative. But we know that zero is neither positive nor negative. How do we fix this program so that zero is treated separately? Ruby gives you the elsif keyword that helps you check for multiple possibilities inside an if..else construct. Try using elsif to fix the code below so that whe n the number is zero, it just prints 0. def check_sign(number) if number > 0 "#{number} is positive" elsif number < 0 "#{number} is negative" else "#{number}" end end Ruby also has an unless keyword that can be used in places where you want to che ck for a negative condition. unless x is equivalent to if !x. Here is an example : Example Code: age = 10 unless age >= 18 puts "Sorry, you need to be at least eighteen to drive a car. Grow up fast!" end The ternary operator ==================== In english, "ternary" is an adjective meaning "composed of three items." In a pr ogramming language, a ternary operator is simply short-hand for an if-then-else construct. In Ruby, ? and : can be used to mean "then" and "else" respectively. Here's the first example on this page re-written using a ternary operator. Example Code: def check_sign(number) number > 0 ? "#{number} is positive" : "#{number} is negative" end Truthiness of objects in Ruby ============================= The conditional statements if and unless can also use expressions that return an object that is not either true or false. In such cases, the objects false and nil equates to false. Every other object li ke say 1, 0, "" are all evaluated to be true. Here is a demonstration: if 0 puts "Hey, 0 is considered to be a truth in Ruby" end # 2.2 Loops in Ruby

Loops in Ruby ============= Loops are programming constructs that help you repeat an action an arbitrary num ber of times. The methods Array#each, Array#select etc. are the most frequently used loops sin ce the primary use of loops is to iterate over or transform a collection, someth ing that we'll learn in the chapter on "Arrays in Ruby." Here we will cover two basic looping constructs you can use to solve most other looping requirements that may come up. Infinite Loops Infinite loops keep running till you explicitly ask them to stop. They are synta ctically the simplest to write. Here goes one: loop do puts "this line will be executed for an infinite amount of time" end The example above does not have a termination condition and hence will run till the process is stopped. A loop can be halted from within using the break command . Now write an infinite loop where the monk will meditate till he achieves Nirvana . Use the break statement once Nirvana is reached. loop do monk.meditate break if monk.nirvana? end Run a block of code N times =========================== Say N is 5, let us imagine how it might look. 5.times do # do the stuff that needs to be done end Well, we imagined it right. It is that simple! Here is a task for you to test your newly learned looping skills. We have a bell outside our monastery that people can ring in times of need. Write a method tha t can ring the bell N times, where N is a parameter passed to the method. # add a loop inside this method to ring the bell 'n' times def ring(bell, n) n.times do bell.ring end end We've only scratched the surface of the various ways in which Ruby lets you writ e loops. However, this should be enough for the most common use cases. Let us kn ow if you need more!

You might also like