Ruby notes 
top

rvm

rvm is very handy when you manage multiple Ruby environment on a machine.

See current ruby interpretor:

$ rvm info ruby

change default ruby interpretor to 1.9.2.

$ rvm use --default ruby-1.9.2

(6/16/2011)

Conditional assignment

||= is useful for setting a value if the variable is nil.

x ||= "default"

The example above sets x to "default" is x is nil.

Add a directory to Ruby’s module search path

$: << "/new/directory/path"

Ruby’s exception handling

begin
  ...
rescue ExceptionClassName => e
end

and

raise ExceptionClassName.new

to cause exception.

Check if a directory exists

FileTest.directory?

Array length

Array.size or Array.length.

To check an object’s class?

Use #class method.

a = 15
a.class

Ruby’s Global variable

Variables prefixed with $ such as $a and $foo.

Ruby’s instance variable

Variables prefixed with @ such as @a and @foo.

What is attr_reader?

It is one of accessors and is a method defined in Module class. You don’t have to write you own methods to read/write instance variables.

There are attr_writer (write) and attr_accessor (read/write)

What is modules?

A Module is a structure(?) that can organize methods and constants. A module has a name. Modules are similar to Classes, but Modules can’t generate instances. There’s no inheritance for Modules either.