Conditional statements and loops are very important while learning any programming language. In this tutorial we will see how the statements and loops work for ruby.
Don’t forget to execute these examples in ruby command line. You can also check out other tutorial on strings before moving on this tutorial.
Check the syntax of if and else conditional statement. You will find that it is very easy to read the ruby code.
if fruit == "apple" puts "This is apple" end if fruit == "orange" puts "This is orange" else puts "No fruit found" end
If you want to expand the program, you can take user input from the command line and then check the condition. You can also add else keyword and nest the conditions as per your requirement.
You can add multiple conditions with the help of elsif keyword. All you have to do is add the elsif where you want to add if or else. It will do the same job as one of these keywords.
elsif fruit == "Mango" puts "This is mango"
Sometimes you want certain operation to process unless some another action takes place to stop it. In such case unless operator can be of use. In other languages we make use of ! not or bang operator.
fruit_basket=empty unless fruit_basket puts "No fruits available" end
Case / When Statement
If you’re familiar with switch case statement then you will have no trouble learning about case when statements.
Check this example.
fruits=5 case when fruits <5 puts "Fruits are less than 5" when fruits > 5 puts "Fruits are more than 5, make salad" else puts "Fruit salad. yay" end
Like any other programming language, while loop in ruby programming is very simple to understand. Take a look at this example.
i=1 while i<10 puts i i+=1 end
This is also easy to understand loop in ruby. You have to specify the condition upto which the loop runs. Think of it like do-while loop.
i=1 until i==10 puts i i+=1 end
The for loop in the ruby programming language is quite different. You can think of it like foreach loop in the php. Let's take example of ruby hash or array to example this in much better way.
fruits = ["mango","orange", "grapes","pappaya"] for item in fruits puts item end
In all the examples given above, have you noticed the usage of keyword end? Do experiment with or without it in these examples and see if you can work with the same results.
Feel free to ask questions or suggest improvements in comments. You can also send me tweet at @maheshkale.