A class is a blueprint.
class Spaceship
end
An instance is something you build from the blueprint.
my_ship = Spaceship.new
A method is an action you perform with your instance.
class Spaceship
def fly
# do things
end
end
Called automatically when you make an instance with .new
.
Use it primarily to set up initial values for variables.
class Spaceship
def initialize(name, speed)
@name = name
@speed = speed
@crew = []
end
end
class Spaceship
attr_accessor(:name, :speed)
def initialize(name, speed)
@name = name
@speed = speed
@crew = []
end
end
Adds an item to an array.
my_numbers = [ 1, 2, 3, 4, 5, 6 ]
my_numbers.push(7)
my_numbers.push(8, 9, 10)
Loops over an array.
my_numbers = [ 1, 2, 3, 4, 5, 6 ]
my_numbers.each do |number|
# my_numbers contains integers so number is an integer
puts number * 2
end
Loops over an array to produce a new array.
my_numbers = [ 1, 2, 3, 4, 5, 6 ]
times_ten = my_numbers.map do |number|
number * 10
end
puts times_ten
#=> [ 10, 20, 30, 40, 50, 60 ]
Loops over an array to produce a single value.
my_numbers = [ 1, 2, 3, 4, 5, 6 ]
final = my_numbers.reduce(0) do |sum, number|
sum + number
end
puts final
#=> 1 + 2 + 3 + 4 + 5 + 6 = 21
enterprise = Spaceship.new
# should be enterprise with lowercase e
Enterprise.fly
Especially initialize
.
class Spaceship
# VERY tough to catch this typo of initialize
def intialize
# do things
end
end
class Spaceship
# Missing attr_accessor for name
def initialize(@name, @speed)
@name = name
@speed = speed
end
end
falcon = Spaceship.new("Milennium Falcon", 400)
# No accessor for name!
puts falcon.name
class
, def
, do
, if..else
all need end
.
class Spaceship
def initialize(name, speed)
@name = name
@speed = speed
end
# MISSING end
It helps a lot to find missing end
keywords when you...
If the former example was properly indented, it would be easy to catch the missing end.
class Spaceship
def initialize(name, speed)
@name = name
@speed = speed
end
# MISSING end