Programming Tutorial: Intro to Ruby! Part 2

, , 1 Comment

Hi everyone, welcome to Part 2 of my Intro to Ruby tutorial series. In Part 1 I covered some very basic concepts such as basic math, variables, and using a text editor to write code. In this tutorial we will continue right where we left off, so fire up your favorite text editor and get ready to learn about input, type casting and testing a condition.

Note: Rather than posting all of the code in bold like I did in Part 1, this tutorial will display code snippets which will be analyzed and explained. This makes more sense because we will be writing longer and more substantial programs in this tutorial compared to the simple one liners we wrote in Part 1. I will still use bold text to refer to code from the snippets.

 

Input (User Interaction)

One of the most essential parts of the applications we use on our computers and mobile devices is how they interact with the user. On our computers we typically interact with Graphical User Interfaces (GUIs) with a cursor. More recent GUI technology include the multi-touch gestures made famous by OSX and touch screens on mobile devices. In Part 1 of this series the basic programs we wrote did not interact with the user at all, they simply output a number or a string of letters. Although we will not be writing any software with GUIs quite yet, we can interact with the user by allowing him or her to type something in the terminal. Let’s start out by modifying the standard “Hello World” application to address the user by his or her name. Type this code into your text editor, save it as HelloWorld.rb, and run it in terminal (instructions on how to do this are covered in Part 1). After it runs, you will see the text “Enter your name: ” in your terminal. Type your name into terminal and hit ENTER.

print("Enter your name: ")
name = gets()
puts("Hello #{name}")

Although this code is still very simple, it has some important functions. First, we simply print “Enter your name: “. It is important to know that we use print instead of puts because puts adds a new line at the end of the printed string, whereas print does not. We want the cursor to remain on the same line as the prompt. On line 2 we use gets() to read in a string when the user presses ENTER. This string is then assigned to the variable name. The last line of code is fairly interesting. In this line, the name variable is embedded into the string. This is done by placing the variable between two curly brackets preceded by a hash mark, as in #{}. This kind of embedded evaluation will only work when your string is surrounded by double quotes. If your code looked like puts(‘Hello #{name}’), where the only difference is that I am using single quotes, your string would be printed exactly like that, or in other words, your name variable would never get printed. One more thing. The parentheses after gets() and also those surrounding the string following print and puts are all optional. The code would run fine without them. Some compilers will give you warnings if you leave them out and parentheses can sometimes help make programs more clear and easy to read. Take note that in future programs we write in these tutorials we may or may not use parentheses.

 

Type Casting

Let’s write something a little bit more complicated (and useful!). This program will help you split the cost of dinner with your friends

print "Enter the cost: "
cost = gets.to_f
print "How many people? "
people = gets.to_f
final_cost = cost/people
puts("The cost per person is $#{final_cost}")

All that is happening in this program is that we are assigning two variables based on the users input (cost and people) and then we do some simple math to calculate the final cost. The only thing that occurs in this program that you don’t know about is the to_f cast method. Type casting is a method of switching from one data type to another. For example, in this program after the user is prompted to “Enter the cost: ” the user enters a string of characters (in this case numbers) which are stored in the cost variable. Later on in the program we perform some division that involves both our cost and people variables. But wait, how do you divide two strings? You can’t. You can only perform mathematical operations on numbers. This is where the to_f method comes into play. As you can see, instead of typing cost = gets like I might have in the last program we wrote, I instead wrote cost = gets.to_f. This to_f method converts our cost string into a floating point. A floating point is simply a way of representing numbers. Another option would be to use to_i, which would convert the string to an integer. The reason I do not do this is because integers get rounded and don’t contain decimals, while floating points do.

 

Testing a Condition: if..then

There is one problem with our “dinner splitting” program that we wrote above: it accepts negative numbers. Consequently, we must check for negative numbers, and when found, set them to zero. This is the new version of the code.

print "Enter the cost: "
cost = gets.to_f
print "How many people? "
people = gets.to_f
final_cost = cost/people

if (final_cost < 0.0) then final_cost = 0.0 end puts("The cost per person is $#{final_cost}")

I simply added what is called an if statement. The code acts very similarly to how it reads. If the final cost of the meal is less than zero dollars, it sets the final cost equal to zero. The first line of the if statement is called the test condition. It is what gets tested before the next line of code gets run. Conditional statements like the if statement are extremely useful when coding and appear all over the place. In addition to the if statement, there are many other extremely useful conditional statements such as the if else statement, the elsif statement, the unless statement, and the case statement. You can learn more about conditional statements here.

Well that pretty much covers it for Part 2. Part 3 will delve further into ruby programming, mainly focusing on how to define methods.

 

One Response

Leave a Reply