Monday, 21 July 2014

Ruby - If Ternary, Until, While

We’re making good progress getting some of the key basics of Ruby understood. Variables are of course central, Arrays allow a more complete way of data handling, Case and If statements are the building blocks of ‘flow control’ in our program.

In looking at these, we’ve also learned a few tricks with getting, printing, chomping and interpolating data and a few neat tricks to present and evaluate data in different ways, to get a True or False state so we know what to do next. That’s quite a bit in a few hours, congratulations if you’ve followed along so far!


With this stuff understood, let’s loop back on ourselves somewhat and add in more detail on a couple of things. To start with, let’s finish off a few more aspects of flow control.
The if statement as we saw it before also has a shorter version, called the ternary or base three operator. Here’s an example:

a = 2
a == 1 ? (puts "Banana") : (puts "Cheese")

Here we set the value of our variable a to 2, in the next line we ask does a equal 1? If True then puts Banana, else puts “Cheese”. In the brackets we could include whatever code we wish to, just like the longer form If statement. However, the ternary or base three version easily gets difficult to read and should only be used for small tasks. This might be concatenating two string or doing a quick piece of math.

In addition to Case and If statements, we also have Until and While loops available to us. These allow us to execute a block of code until a certain condition is true or false.

·         For Until, the code executes so long as a condition is evaluated to false
·         For While, the code executes so long as a condition evaluates to true

First, here’s an example of Until in action:

c = 1
 until c == 6
   puts "C = #{c}"
   c +=1
We’ll see five lines printed to screen, stopping when c evaluates to 6, as the condition is now true. Note in the last line how we increment the value of our variable.
Let’s look at an example of While in use:

d = 1
 while d < 5 do
   puts "D = #{d}"
   d +=1
As with the Until, here we’ll see five lines printed and the code will stop executing once the condition is false. The do keyword is optional. However, it’s more correct to use it, just like adding then in our If statements.


Read More