Ruby on Rails Course 2009

Ruby: Basics

Interactive Ruby (irb)

Irb is an interactive interface to Ruby

Datatypes

Almost everything in Ruby is an object. Try the following in irb:

123.class
999999999999999999999999999999999999999999999.class
nil.class
true.class
"hello world".class
:symbol.class

Constants

  • Constants always start with capital letters
  • You can change constants in Ruby, but you shouldn’t
Constant = 5    # This is a constant
constant = 5    # This is not

Symbols

Every time you type a string, Ruby makes a new object:

irb> "live long and prosper".object_id
=> -606662268
irb> "live long and prosper".object_id
=> -606666538

Notice that the object ID returned by irb is different even for the same two strings.

To save memory Ruby has provided “symbols”

irb> :live_long_and_prosper.object_id
=> 150808
irb> :live_long_and_prosper.object_id
=> 150808

Symbols are often used as hash keys.

Hashes

  • Hashes are like dictionaries
  • You have a key, a reference, and you look it up to find the associated object, the definition.
hash = { :leia => "Princess from Alderaan", 
         :han => "Rebel without a cause",
         :luke => "Farmboy turned Jedi" }

Arrays

Arrays are a lot like hashes, but the keys are always consecutive numbers.

array = ["This", "is", "an array"]
puts array[0] # => "This"
puts array[3] # => nil

Using an out of range index will return nil.

Strings

  • String literals
  • Single quotes
  • Double quotes
  • Escape sequences
  • Very long strings

String Literals

puts 'Hello world'
puts "Hello world"

puts "Betty's pie shop"
puts 'Betty\'s pie shop'

Single Quotes

Single quotes only support two escape sequences:

\' - single quote
\\ - single backslash

Double Quotes

  • Double quotes allow for many more escape sequences than single quotes.
  • You can also embed Ruby code inside of a String literal (interpolation)
name = "bob"
puts "Your name is #{name.capitalize}"

Escape Sequences

\" - double quote
\\ - single backslash
\a - bell/alert
\b - backspace
\r - carriage return
\n - newline
\s - space
\t - tab

Very Long Strings

There are several methods for this, but here’s a simple one:

poem = %{My toast has flown from my hand
And my toast has gone to the
moon.
But when I saw it on television,
Planting our flag on Halley's
comet,
More still did I want to eat it.}

Numbers

Integers and Floats

The basic numeric datatypes in Ruby are integers and floats.

Number operators:

+  addition
-  subtraction
/  division
*  multiplication
** exponent (e.g. 26**3 == 263)
%  modulus (the remainder of two divided numbers)