Ruby On Rails - Week 4


Welcome to Ruby on Rails From Scratch Week 4! This week we're going to talk about ruby syntax. After this tutorial, I believe that you'll have a much better understanding of the framework and feel much more comfortable doing things by yourself. Oh yeah, and there's a surprise this week - a screencast! So without further ado, here is week 4!

Catching Up

If you haven't read Parts 1, 2, or 3, it is strongly advised that you review them before continuing on with this tutorial.

Last Week...

Last week, we learned more about the framework. Specifically, we talked about things like interacting between different controllers by inheriting actions, rendering, and redirecting.

This Week

As you might expect, you can hardly teach an entire language in one tutorial, so we probably will have to span just essential ruby into two tutorials. Anyway, for this tutorial I envision us to cover numbers and strings. These are probably the two most basic and essential techniques in the ruby language. In fact, once you get the hang of strings and numbers, you probably won't even think anything of them when you use them.

Number Basics

One type of class in the ruby programming language is numbers. Actually, there are two types of numbers; integers and floating points. Integers are the default number. If you remember back to math class, integers cannot have decimal places. Likewise, in floating points, you can have a decimal point. Another important point is that numbers are eventually converted to a string, but after almost everything else is executed. Therefore, numbers and strings cannot do things together like concatenate.


Integers are the default numbers used in the ruby language. Use them if you are not going to have to deal with a decimal point. For example, integers are good for counting by ones. If you perform a calculation in ruby as an integer, and it has a decimal point it will essentially be chopped off:


<%= 7/4 %>

Result: 1

Floating Point

So, how exactly do you use floating points instead of integers? There is a method that converts it:

<%= 7/4.to_f %>

Result: 1.75

Converting Between Different Classes

Often you will want to convert one type of object to another so you can make it interact with objects of that class. Luckily, ruby makes it really easy:

Convert to String:

<%= '5'.to_s %>

Convert to Integer:

<%= '5'.to_i %>

Convert to Floating Point:

<%= '5/3'.to_f %>

Floating Point Methods

When you convert a number to a floating point, you gain additional methods to apply to it. The most important ones are how to manipulate the number when rounding.


<%= (5/3.to_f).round %>

In case you have a floating point number in which you don't want the decimal place, you have basically one of three options. Rounding will round up or down to the nearest whole digit. It will round to the closest digit. (ie. 2.3 will be 2 and 2.55 will be 3) In this case, the result would be 2.


<%= (5/3.to_f).ceil %>

Just like the name might suggest, the ceil method will bump the floating point up a digit. So if it's 1.2 it will be 2 and if it's 1.6 it will still be 2. In this case the result would be 2.


<%= (5/3.to_f).floor %>

Floor is the opposite of ceil, in that it bumps it down. In other words, you can think of it like it is just cutting the decimal point off and/or like what would happen in a normal integer. In this case, the result would be 1.

Counting Technique

Often when you're programming, you have to count. There's a shorter method in ruby, rather than variable = variable +1:

Add 1 to the variable: += 1

Subtract 1 from the variable: -= 1

Multiple the variable by two: *=2

Divide the variable by two: /=2

So applying the above, let's apply it:

Count: <%= count = 5 %> 
Add 1 (+=): <%= count += 1%>
Subtract 1 (-=): <%= count -= 1%>
Multiply by 2 (*=): <%= count *= 2%>
Divide by 2 (/=): <%= count /= 2%>

Which produces this:

Ruby on Rails Numbers

String Basics

We've already dealt with strings a little bit. Remember all of that 'Why Hello' stuff back in week 2? If you don't be sure to check back. We already delt with recognizing strings and concatenation. For a quick review here is an excerpt from the string section:

String Concatenation

You can create a string in ruby by using quotes. You can even combine strings together by concatenating them together. There are several ways to do this. The most logical, is to treat it like math:

  <title>String Demo</title>

  <%= 'This is kind of boring' %><br>
  <%= 'Will I combine' + 'With You?' %>

When we output this we show how exact ruby is though. Notice there is no space between combine and with. To add a space just add one before the quote at the end of combine or before with.

Other ways of combining strings

You can combine strings two other ways as well. One method would be

<%= 'Will I combine'.concat('With You?') %>

This format is the standard for most modifiers. We will cover more ways later. We also have a third way to combine strings.

<%= 'Will I combine' << 'With You?' %>

Please note though that with this last method you cannot have an empty string. So if you're going to be filling the string in with a variable, I'd use one of the first two, just in case the variable doesn't have a value.

Other String Methods

Here are some more methods you can apply to strings. Most are self-explanatory so I will just demonstrate the code. For all of these methods, you can assume that I've already declared a local variable named text .


<%= text.capitalize %>

Swap Case

<%= text.swapcase %>

Up Case

<%= text.upcase %>

Down Case

<%= text.downcase %>


<%= text.reverse %>

More Methods


 <%= 'Goodbye' + ' whitespace    '.strip + 'And Hello!' %>

The strip method allows us to strip out white space from the string.


<%= text.insert(5, '*Excuse Me* ') %>

Inserting is almost like the concat method, except you're passing two arguments instead of one. (The additional argument being the location in the string to insert the text into) Also note that inserting into a variable will permanently insert the string into the variable.


<%= text.length %>

The length method doesn't return anything in the string, but rather it tells you something about the string; specifically the length of the string.

Daisy Chaining Methods

<%= text.swapcase.reverse.strip %>

Similarly to JQuery, a nice feature about ruby methods is the chainability which allows less code to be written.

Single or Double Quotes?

You can use either double or single quotes in ruby. It doesn't matter. Although there are some specific occurrences where you might want to use one over the other; as a general rule, pick one and just stick to it. Now I will list some scenarios where you would prefer one over another.

A Quote in the String

If you have either a single or double quote inside the string itself, you might want to wrap the string around the other kind of quote. On the rare chance that you have a double and a single quote inside the string, you can use the back slash (\) before the symbol to indicate that it shouldn't end the string.

<%= "Sally's cat is brown." %>
<%= 'The "cat" is brown.' %>
<%= 'Sally\'s "cat" is brown.' %>
<%= 'I love the \\ mark.' %>

The above code would output as the following:

Sally's cat is brown.
The "cat" is brown.
Sally's "cat" is brown.
I love the \ mark.

Executing code in the middle of a string

Normally it is pretty challenging to execute code in the middle of a string. In ruby, there is an even easier way than concatenating:

<%= "This string #{'*hguoC* '.reverse * 3} just got interrupted."%>

As you can see the above code allows you to perform ruby code inside of a string. Note though, that you have to use double quotes with the string.

Final Thoughts

Ok, so hopefully you have a much better and deeper understanding of numbers and strings, and how to work with each of them. Next week we'll talk about more ruby syntax; particularly ranges and hashes. Once you know how to work with those, your possibilities will grow endlessly. Make sure you have a good handle on this for next week as well; try experimenting and seeing what works. As usual, if you found this helpful, please digg it!

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.

Related Posts
  • Code
    Object-Oriented Programming in WordPress: TypesWordpress oop
    In the last post, we took a look at classes which are the building blocks of object-oriented programming. Before we go any further, we need to take a survey of some of the data types that PHP offers. Though we won't be reviewing every type in this particular article, we're going to take a look at some of the more popular types that we'll be using in WordPress development.Read More…
  • Code
    Preventing Code InjectionCsrf dotnet retina preview
    Often, websites seem to exist primarily to put something into a database in order to pull it out later. While other database methods, such as NoSQL, have gained popularity in recent years, data for many websites still resides in the traditional SQL database. This data often consists of valuable personal information such as credit card numbers and other personal information of interest to identity thieves and criminals. Hackers therefore always look to get this data. One of the most common targets of these attacks is the SQL databases that lie behind many web applications through a process of SQL Injection.Read More…
  • Code
    Validation and Exception Handling: From the UI to the BackendProcedural to oop php retina preview
    Sooner or later in your programming career you will be faced with the dilemma of validation and exception handling. This was the case with me and my team also. A couple or so years ago we reached a point when we had to take architectural actions to accommodate all the exceptional cases our quite large software project needed to handle. Below is a list of practices we came to value and apply when it comes to validation and exception handling.Read More…
  • Web Design
    Walk Users Through Your Website With Bootstrap TourTour retina
    When you have a web application which requires some getting used to from your users, a walkthrough of the interface is in order. Creating a walkthrough directly on top of the interface makes things very clear, so that's what we're going to build, using Bootstrap Tour.Read More…
  • Code
    Mobile Development
    C++ Succinctly: TypesPreview image@2x
    C++ contains the same familiar keywords that you recognize from C#. This is unsurprising given that both are C-like languages. In this article, we'll take a look at the types available in C++.Read More…
  • Code
    Creating a Photo Tag Wall With Twilio Picture Messaging & PHPProcedural to oop php retina preview
    Twilio's recently announced Picture Messaging has vastly opened up what we can do with text messaging, now we can attach photos to our text messages and have them get used in different ways. In our case, we are going to build a Photo Tag Wall, which will contain photos linked to tags that will be displayed on a website.Read More…