

|
|
| Language | Framework |
Let's get started
IRB: Interactive RuBy
>> 4
>> 4 + 4
Everything is an object
“test”.upcase
“test”.class
“test”.methods
Everything evaluates to something
2 + 2
(2+2).zero?
Methods are messages
thing.do(4)
thing.do 4
thing.send "do", 4
Operators are Methods
1 + 2
1.+(2)
1.send "+", 2
# is a comment
You don't need semicolons
Use parens when you need them
>> "Hello".gsub 'H', 'h'
=> "hello"
>> "Hello".gsub("H", "h").reverse
=> "olleh"
Variables, symbols, constants
There is only one representation of a given symbol in memory, so it really means "the thing named :this_is_a_symbol" to the ruby interpreter. In ruby, we prefer symbols over hardcoded globals or strings. They're very lightweight.
Collections
Arrays are sized dynamically and can be of mixed types.
a = [1, 2, 3]
a.push "four" #=> [1, 2, 3, "four"]
a.pop #=> "four"
a[0] #=> 1
Hashes are like an associative map
states = {"MA" => "Massachusetts", "CA" => "California"}
states["MA"]
my_hash = {:a_symbol => 3, "a string" => 4}
my_hash[:a_symbol]
=> 3
String interpolation
"string #{ruby code} string"
>> a = "world"
>> puts "hello #{a}"
hello world
>> a = 2
>> puts "hello #{a}"
hello 2
>> a = nil
>> puts "hello #{a}"
hello
Iteration
my_array = ["cat", "dog", ”world"]
my_array.each do |item|
puts "hello " + item
end
my_hash = { :type => "cat",
:name => "Beckett",
:breed => "alley cat" }
my_hash.each do |key, value|
puts "My " + key.to_s + " is " + value
end
Classes and methods
class Thing
def return_something
"something"
end
end
class Thing
def do_something(a,b)
a + b
end
end
var
@var
@@var
$var
VAR
var # could be a local variable
@var # instance variable
@@var # class variable
$var # global variable
VAR # constant
Methods can take blocks, which are like anonymous functions.
my_array = ["cat", "dog", ”world"]
my_array.each do |item|
puts "hello " + item
end
def do_something
yield
end
[1, 2, 3].each do |item|
puts "#{item} is #{item.even? ? "even" : "odd"}."
end
Blocks can also return a value. Map translates each item in an array.
>> ["hello", "world"].map{ |string| string.upcase }
=> ["HELLO", "WORLD"]
def print_even_or_odd(array_like_thing)
array_like_thing.each do |item|
puts "#{item} is #{item.even? ? "even" : "odd"}."
end
end
print_even_or_odd [1, 2, 3]
print_even_or_odd 1..3
method_missing
class Fixnum
def even?
self % 2 == 0
end
end
1.even? #=> false
Have fun!