Ruby On Rails Week 4
videos

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

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.


Add Comment

Discussion 35 Comments

  1. Loved that you cover more of ruby as you go.
    Getting people into Ruby as well as Rails is important.

    Thanks!

  2. Ian Crust says:

    weeks 5 – 25 will cover getting a RoR app up and running on your web server…

  3. Barttos says:

    Mmm, realy good tutorial, more tutorials of this type! :-)
    Wainting next tutorial :-)

  4. Connor says:
    Author

    Glad you guys enjoyed it!

  5. Shane says:

    Good coverage. Thanks.

  6. insic says:

    WOW! great! I love the screencast. Keep it up.

  7. Jim Neath says:

    You can also use %Q to quote strings:

  8. Excellent stuff, many thanks :)

  9. Aj says:

    thank you nettuts

  10. Zoran says:

    1000.times{ puts “I Love Rails”}, but(luckily) is not so easy as claims people on rails web site!
    But once u learn satisfaction is big.
    So thanks & all the best!

  11. Joel says:

    Thanks! These tutorials are great.

  12. Alex says:

    Awesome, thanks. btw, it’s pronounced net Toots, like tutorials ;) Thanks for the screencast!

  13. cary says:

    I really want the next one to come out. :) soon!

  14. Jesse says:

    Where are the next tutorials? That is a bummer when people start these and give so much good info but then get distracted and never finish… So far the tutorial has been one of the best out there though!

  15. Connor says:
    Author

    Yeah…sorry about the delay. Right now I’m working on a separate mini series that will focus on practical application of ruby on rails techniques- a little different version of teaching it. Then, hopefully I will be able to resume this series.

  16. Dixon Crews says:

    I just read/watched all of these and I have to say they are GREAT!

    Please keep doing the screencasts! They really are the best way to learn for us visual learners. :)

  17. Kevin says:

    Hi can someone please answer me. what should you learn first PHP or Ruby on Rails?
    thank you.

  18. Tim says:

    Great tuts, followed em all today.
    Would love to see the others coming soon!

  19. Diego says:

    What happened to week 5!?

  20. Mark Darling says:

    Will week 5 ever appear?

  21. surender says:

    A great article to go around with ROR.

  22. Bryan says:

    Hope week 5 will be out today. We’re already excited ;)

  23. Bryan says:

    Connor, your tutorials are great! Why don’t you write a book? :)

  24. Younus says:

    Hey Kevin,

    The syntax and coding structure of PHP and RoR are almost different. PHP is similar to C, C++, on the other hand RoR relates to Perl, Python. But I think PHP is an wonderful language. You can have a great deal of resources and help in web. It’s ranking is 4 whereas RoR is 11.

    http://www.tiobe.com/index.php/content/paperinfo/tpci/index.html

    That’s why u should learn PHP first!

  25. Massimiliano says:

    Hi Connoer,
    your tutorials is fantastic..
    i have learn many things. :)
    But when weeks 5 will be released ????

    If you don’t have time to write this, can you suggest me book, tutorials or more to proced my learning ???

    tnx a lot

  26. Have followed some of your work am impressed.

    Would like to give you a project or two, after explaining to you what I need and discussing if it is possible.

    Please email me so that we can discuss it.

  27. Sarika says:

    Where is Week5?

  28. Nate says:

    3 weeks and 4 days. Where’s week 5? :(

    Still, AWESOME series so far!

  29. Nate says:

    Wait, was this October 27 of 2008? Now after reading some comments It was!

  30. Chloe24 says:

    This is the best time to say that you impressed us with your nice tought referring to this good topic. So, we will attempt to write the legal dissertation on the ground of your stuff. Or believably, it’s doable to notice the dissertation writing service.

  31. Don Blaire says:

    Super tutorial. Totally been enjoying the information.

  32. Finding some issues, when solving this:
    when I type this:
    (15.to_f/1000).round(3).to_f
    I get this: 0.015 (which is true)
    but when I type this:
    (10.to_f/1000).round(3).to_f
    I get this: 0.01 (whereas I should get 0.010)

    Any help would be highly appreciated.

    Thanks
    Puneet

    • Alex says:

      Generally people don’t write 500.00 but instead 500. I’m not 100% sure how to add the extra trailing zero, though. I think it’s how it’s supposed to be read.

  33. kamna says:

    Your tutorial.. is very clear and informative! Could you please provide week 5 link?

  34. keith says:

    your tutorials are the best! please keep writing them!!

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.