A class is a blueprint.
class Spaceship
endAn instance is something you build from the blueprint.
my_ship = Spaceship.newA method is an action you perform with your instance.
class Spaceship
def fly
# do things
end
endCalled 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
endclass Spaceship
attr_accessor(:name, :speed)
def initialize(name, speed)
@name = name
@speed = speed
@crew = []
end
endAdds 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
endLoops 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 = 21enterprise = Spaceship.new
# should be enterprise with lowercase e
Enterprise.flyEspecially initialize.
class Spaceship
# VERY tough to catch this typo of initialize
def intialize
# do things
end
endclass 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.nameclass, def, do, if..else all need end.
class Spaceship
def initialize(name, speed)
@name = name
@speed = speed
end
# MISSING endIt 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