Irb is an interactive interface to Ruby
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
Constant = 5 # This is a constant
constant = 5 # This is not
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.
hash = { :leia => "Princess from Alderaan",
:han => "Rebel without a cause",
:luke => "Farmboy turned Jedi" }
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.
puts 'Hello world'
puts "Hello world"
puts "Betty's pie shop"
puts 'Betty\'s pie shop'
Single quotes only support two escape sequences:
\' - single quote
\\ - single backslash
name = "bob"
puts "Your name is #{name.capitalize}"
\" - double quote
\\ - single backslash
\a - bell/alert
\b - backspace
\r - carriage return
\n - newline
\s - space
\t - tab
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.}
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)