Code Academy Notes Week 1

Here are my notes from Code Academy week 1.

2012-01-12_08.14.41
Almost everything is lower-case
Methods: def method_name to name

Lists in Ruby
Very important to be good with lists.

landmarks = [ "Wrigley Field", "Millenium Park", "John Hancock Center" ]

This is an array. You do not specify the size.
Iterate through array:

landmarks.each do |name|
  print_landmark name, "100"
end

irb is “Interactive Ruby”
for a variable or a class, you can type “x.methods” in irb to get all the methods you can call on it
to print them alphabetically, x.methods.sort
to get out of irb, type “exit”
An array is a list of single elements
A list of pairs is a hash:

landmarks = { "United Center" => "90",
              "Wrigley Field" => "40",
              "Millenium Park" => "0",
              "John Hancock Center" => "15" }

Braces instead of brackets
Iterate through hash:

landmarks.each do |name, fee|
  print_landmark name, fee
end

Any methods created in a variable are local to the method. They only have meaning within the method

CSS

Back to Ruby: String interpolation, use the pound and braces:

puts "#{landmark_name} --- #{cost_of_admission}"

Interpolation is a bit faster

To set the variable, single equal sign:

x = 10

To compare the variable, double equal sign:

x == 10

Ruby classes:

attr_accessor :name_of_symbol

give it a symbol (colon and some name)

Variables: @name, @address, @cost: Private variables to that object
attr_reader will allow you to set it only at initialization, and only read thereafter
You could make a variable @api_key to be private, just don’t provide an attr_accessor
In pure Ruby, there is no way to ensure that @cost is always greater than 0. I would have to write my own methods for that.

Image from Wikimedia, assumed allowed under Fair Use. Image from the Vatican Virgil, a 5th century manuscript of poems by Virgil.