Learning to read Ruby on Rails code – a cheatsheet for absolute beginners

June 28, 2009 at 11:24 am 11 comments

Ok, I wish somebody made this post when I was just learning Ruby on Rails, so enjoy 😉 This is version 1.0, so if you find any errors or want an extension, let me know:

1. @variable – @ sign is an indicator of an instance variable. Actually it’s incorrect, as Ruby does not have variables, it has only Classes and their instances. So for example assigning like this: @some_string = “some text” makes @some_string an instance of a String class. And it makes it possible to access methods for this class. So you can use @some_string.length to get a length of a string. There’s also the @@variable, which is a class-level variable (accessible by anywhere within the class), also quite rare.

2. No “;” needed. You do not need to explicitly finish each line with a semi-colon, unless you want to write multiple operators on a single line, like this: a = 5; puts a; puts a+5;

You can also use “\” for continuation of a line. There is a related notation that you might see which is:

something = longname + anotherlongname \
+ z

“\” is used to indicate to Ruby that the line continues, if the continuation is ambiguous, like in the example above.

3. = and ==. Just as in PHP, the first is for assignment, the second is testing equality.

4. “some text #{@variable} and some more text” – use this to insert variables or actually any(!) ruby expression, eg. #{2*@variable} or #{@variable.capitalize} will work too. The parsing happens only for “quotes”, not the ‘quotes’. Also, if you are simply referring to a variable you can omit the curly brackets, so just use ” some text #@variable and more text”

5. $variable – a Global variable, same meaning as in PHP. Rarely seen in the Ruby on Rails world.

6. something.blank? – a “?” is just a part of the method “blank?” name. What makes it useful is that you can understand that this method returns a boolean.

7. something.do! – Again, just a part of the method but indicates that this is a more dangerous version of a normal method. A standard example – @array.sort – will return a new sorted array, whereas @array.sort! will resort the existing @array, modifying it.

8. variable – a local variable is without any variable indicator. Actually, this is probably the most confusing notation for novices as variables (really objects or instances) and method calls can look the same.

9. Constant – constant is any name capitalized (!). Constants in Ruby can actually be changed, but you will get a warning.

10. something.method – easy to guess, what comes after the dot is a method call. Method call can omit the brackets, so when usually you would write something.method(), in Ruby you don’t have to. Also Ruby is very flexible in the use of brackets even if you pass parameters to it, so…

11. link_to “Artist”, artists_path – So link_to is a method and brackets are omitted. You could just as well write link_to(“Artist”, artists_path). Bracket omission is very common in Ruby on Rails. For example belongs_to :person is the equivalent to belongs_to(:person), but you would rarely see the latter notation.

12. curly brackets { } – these are most of the time an indicator of a block, but will also be used for hashes (more on them later). More on blocks here.

13. @array[0] or array[0] or string[0], etc. – This is similar to PHP, so you should not have a problem with that, this is a notation to access the elements of the array.

14. 1..10 – this is a range from 1 to 10. And this 1…10 is the same range, but excluding 10.

15. {1=>”one”, 2=>”two”} – this is a hash definition.

16. :some_symbol – Ok, one of the more confusing things, a symbol is used pretty heavily in Rails. Think of it as a name without a value. You might ask why not use “some_value” instead of :some_value. As I understood, it all goes in the treatment of “some_value” by Ruby – it takes more memory to store this instead of a symbol and has more overhead, as “some_value” is also an instance of a String (don’t believe me? test it – “some value”.class), and you can write things like “some_value”.length. Another thing you will get used to is that :some_value is a good indicator of a parameter.

17. # – This is for comments. Simple enough. The multiline comments do not exist in Ruby, so the best way is to use a “false” block, like this: if false do … some code you want to comment out.. end

18. @variable = “something” if @othervariable.blank? – This is actually quite easy to read, it’s called “if modifier”. It’s the same as saying if @othervariable.blank? then @variable = “something” end. So, the modifier saves you typing 7 characters and looks more natural language-like. The modifier can be used only for simple one-line operators, but it’s very common in Ruby on Rails. You can use the same logic for the unless or while operators, which is the opposite of if in that case.

19. def methodname..end – this is the definition of a method. Again, simple enough. def self.methodname..end is a definition of a singleton method (a method that cannot be called on an instance, only on the class itself).

20. method.each or @variable.each – a very common iterator that usually comes with a block. For example, if you want to go through each item in an array and display it, you will write something like this: @some_array.each { |item| puts item }

21. class Artist < ActiveRecord::Base
This is a class definition for Artist. “<" means that it's a subclass of ActiveRecord::Base. "::" means that Base is a class within the ActiveRecord module.

22. SomeClass::CONSTANT – Class can define a constant and you will access it that way.

23. <% ruby code here %> – same as <? php code ?> – allows to use inline ruby in the templates.

24. <%= ruby code here %> – same as <?= php code ?> – uses inline ruby and outputs the result in the browser. You can also comment out inline ruby like this: <%#= ruby code here %>. Finally, you might also see this: <%= … -%>, it just removes unnecessary white space from the inline ruby, so that the output HTML is prettier.

25. =~ – this is a Ruby operator for pattern matching. It’s not available for most variable types, but can be used for strings.

26. @array << “here is another item for you” – this is how you can append to many types of variables, including strings and arrays.

27. x==1 ? y:z – conditionals. If x == 1 then y else z

28. %w[this is a test] # Same as: [‘this’, ‘is’, ‘a’, ‘test’] – This example is lifted from the great Ruby Programming Language book. A quick way to create an array out of a space delimited string. There is also a %W which will create an array with “items” instead of %w ‘items’. (See above for the difference in “string” and ‘string’).

29. Implicit method return. Justin adds:

A method automatically returns whatever the last value is, eg.

def multiplyTwo x
x * 2

the result of ‘x * 2′ is returned from the method, you don’t have to explicitly use the return keyword

30. True / false definitions. Nil and false return false, while everything else returns true. So 0, 1, “” will all return true, for example.

31. variable ||= “hello”. This operator is very often used, basically what it means – assign “hello” to variable if it’s not defined / nil and do nothing if it’s not nil. Good way to initialize variables.

32. User.name rescue nil. This notation is used to get around the NoMethod Ruby error. If name is not defined, the exception is rescued and nil is returned. This is now somewhat deprecated, as you can use try (comes with Rails 2.3.2) or andand methods (here’s the info).

33. something.each(&:some_method). This can be seen in the Rails code and is a short notation for a simple block like this:

# The same as people.collect { |p| p.name }

Entry filed under: Uncategorized. Tags: , , .

Split a string in two (or three) My Ruby on Rails dev environment

11 Comments Add your own

  • […] January 9, 2006 28 June 09 Note – I am planning to update information in this post, as some of the things are easier to do now than they were then. 28 June 09 Note 2 – If you are new to Ruby / Rails, you should also get yourself acquainted with the Ruby syntax here. […]

  • 2. Justin  |  June 30, 2009 at 1:05 am

    Just another thing that I originally overlooked when learning Ruby…

    A method automatically returns whatever the last value is

    def multiplyTwo x
    x * 2
    (the result of ‘x * 2’ is returned from the method)

    you don’t have to explicitly use the return keyword

  • 3. allaboutruby  |  June 30, 2009 at 7:44 am

    Justin – thanks for the comment! I willdefinitely add it to the list

  • 4. Alice  |  September 8, 2009 at 10:46 pm

    ; and \ are VERY different.
    They shouldn’t be mentioned in the same sentence as “PHP” and “RoR”.

    • 5. allaboutruby  |  September 9, 2009 at 8:15 pm

      Yes, they are very different. I will probably need to split them up, thanks!

  • 6. Lino Silva  |  January 3, 2010 at 2:45 pm

    This is just great. Thanks a lot for this simple and to-the-point explanation.

  • 7. harry  |  November 12, 2010 at 7:40 pm

    This is exactly what I needed. Thanks

  • 8. Don Mapp  |  November 28, 2010 at 3:54 pm

    The problem with most programmers is that when they get proficient they forget the time when they were learning. Ruby on Rails, is great because, apart from its power it unleashes, it has so many people like yourself who are prepared to give a helping hand to those struggling to get to grips with its coding.
    Many thanks

  • 9. mrm  |  May 11, 2011 at 3:40 pm

    just making some correction of item 17. ruby has multiline comments:

    comments here!

    just put the comment between ‘=begin’ and ‘=end’. 🙂

  • 10. park  |  April 11, 2013 at 2:09 pm

    Thanks, it is just what I need

  • 11. Y Tế Sức Khỏe Và Đời Sống  |  June 12, 2014 at 10:20 am

    Thanks. Good Article


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed

Recent posts

Starting to learn Rails?


Get Kindle - the best e-book reader, that I personally use, and the only one that you can read on the beach - very useful: Kindle Wireless Reading Device (6" Display, Global Wireless, Latest Generation)

%d bloggers like this: