Learning Ruby: First Impressions

Ruby (and Rails) seem to be designed to make the code look very like natural language. This makes the code very easy to read but less easy (for someone new to Ruby) to write. It seems like there is a lot you are required to know, although maybe a Ruby programmer looking at CSharp for the first time would think that there is a lot to know?

There are a lot of conventions in Ruby, the most obvious is that method names are all lower case with words separated by underscores. Combine this with other syntax such as brackets surrounding method parameters are optional, ‘unless’ being the inverse of ‘if’, and allowing the if (or unless) statement to be placed after the statement that is to run if it is one line and you get code that looks very close to natural language.



redirect_to root_path unless user.authorized?

The next things that strike you are the use of symbols and hashes, they seem to appear everywhere.

Symbols are similar to global constants in other languages, except they do not have to be declared and they aren’t assigned a value. A symbol is a colon followed by a name (:red, :monday, :ford etc). Ruby assigns a value to the symbol behind the scenes and this value will match wherever it is used in a program.

A common use of symbols is as keys for hashes. Hashes are declared as a number of key value pairs enclosed in braces. The key and value are separated by ‘=>’.

week = {
    :sunday    => 'weekend',
    :monday    => 'workday',
    :tuesday   => 'workday'

Hashes are often used to pass a variable number of parameters to a method:

validates :email,     :presence   => true,
                      :format     => { :with => email_regex },
                      :uniqueness => { :case_sensitive => false }

Two things to note with this common pattern:

  • If the hash is the last parameter in the method definition, it doesn’t require curly braces around it.
  • The value of a hash item can be another hash (and this should have braces).

Code blocks are chunks of code surrounded by either braces or do … end and don’t appear too different from CSharp’s anonymous methods. A code block can be passed to a normally defined method and the yield keyword used to run the code block, passing parameters if needed.

This is only a first pass, but Ruby doesn’t look too far from CSharp. I haven’t mentioned the obvious difference that Ruby is dynamic but I doubt anyone would be ‘surprised’ by that.

Leave a Reply