The "What the hell is that?" guide to Ruby

May 22nd, 2006

If like me you are coming from a Java development background or even other languages there are a few things with Ruby you just gotta say “What the hell is that?” when it comes to reading code.

Reading other people’s code is the best way to learn a new language. Period. But there is a few things with Ruby you may not be used to, well I wasn’t anyway.

I do suggest everyone interested in Ruby take’s a browse through The Ruby Book

Here are a few of them:

:symbol

The : character you are going to see a lot, especially in RubyOnRails. The : character in front of a lowercase word makes it a Symbol.

According to the book:

A Symbol object represents a Ruby name and is generated automatically using the :name literal syntax. The same Symbol object will be created for a given name string for the duration of a program’s execution, regardless of the context or meaning of that name.

What does this mean? Well generally symbols are used in Hashes as the key, because it is a nice readable key to use. They are also used to make APIs more readable.

For instance in Rails you used them in the find method.


  review = Review.find(:first, :conditions => ['name = ?','stuarte'])

The => operator is used to assign a value to :conditions in a Hash. But the :first is used to indicate you want the first element.

def method? or def method!

This one had me foxed for a little. The use of a ? or ! after a method signature is actually a convention that isn’t enforced, instead it tells you a little about what the method does.

The ? character indicates that a method is a query that should return true or false. For instance


   test_array = Array.new
   test_array.nil?       >> false
   test_array.empty?     >> true

This tells you that the your object is not Nil but is empty.

The ! character indicates that a method in some way affects the state of the object it is called on. For instance


   newstring = mystring.chop

Will return a new modified string, while

   newstring = mystring.chop!

Will actually modify mystring.

The convention is not enforced so don’t rely on it but do use it in your own methods. By nice to people reading your code.

%w(what the hell)

%w is a way of defining arrays. So


  %w(what the hell)     >> ['what', 'the', hell']

You can also have %W which allows you to include interpolations of code such as:


  array = %w(what the hell)     >> ['what', 'the', hell']
  %W(tutorial on {array})  >> ['tutorial', 'on', ['what', 'the', hell']] 

this..that

The .. is used to create a Range object. You can create a Range object between any two objects which can be compared with <=> and have a succ method to give the next object in the sequence. This includes numbers, strings and anything else you define with the two methods above.

so: