Ruby On Rails Week 4

Ruby On Rails - Week 4

Oct 27th in Screencasts by Connor Zwick

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!

Author: Connor Zwick

I am a freelance web designer. I am currently renovating my personal site, which will be up within the month hopefully. I know HTML, CSS, Javascript, JQuery, PHP, Flash, and Ruby on Rails. I am also doing several website for pay currently. As well as designing a web site for a robotics team for free. This website will feature a lot of what I will cover in this tutorial. I have also coded a media management site and blog in Ruby on Rails. I also have extensive Photoshop experience.

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.


Related Posts

Check out some more great tutorials and articles that you might like

Enjoy this Post?

Your vote will help us grow this site and provide even more awesomeness

User Comments

( ADD YOURS )
  1. Christian Dalsvaag October 27th

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

    Thanks!


  2. Ian Crust October 27th

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


  3. Barttos October 27th

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


  4. Connor October 27th

    Glad you guys enjoyed it!


  5. Shane October 27th

    Good coverage. Thanks.


  6. insic October 27th

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


  7. Jim Neath October 27th

    You can also use %Q to quote strings:


  8. Ben Griffiths October 27th

    Excellent stuff, many thanks :)


  9. Aj October 27th

    thank you nettuts


  10. Zoran October 27th

    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 October 28th

    Thanks! These tutorials are great.


  12. Alex November 12th

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


  13. cary November 27th

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


  14. Jesse December 1st

    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 December 7th

    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 December 14th

    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 January 5th

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


  18. Tim January 8th

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


Add Your Comment

( GET A GRAVATAR )
  • Gravatar

    Your Name January 9th

Arrow