Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

Ruby On Rails - Week 4

by

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

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:

Calculation:

<%= 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.

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.

Ceil

<%= (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.

Floor

<%= (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:

		
 Counting
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:

<html>
  <head>
  <title>String Demo</title>
  </head>

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

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 .

Capitalize

<%= text.capitalize %>

Swap Case

<%= text.swapcase %>

Up Case

<%= text.upcase %>

Down Case

<%= text.downcase %>

Reverse

<%= text.reverse %>

More Methods

Strip

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

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

Inserting

<%= 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.

Length

<%= 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.


Advertisement