ruby · level 2 · unit 6 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
sets up each new object with its own data.
When you call .new, Ruby runs a method called initialize inside the new object. Any arguments you give .new are passed on to it, so Pet.new("Rex", 3) hands it a name and an age.
An starts with @, like @name. It belongs to one object and lasts as long as that object, so every method in the class can use it. Two pets each have their own @name.
class Pet
def initialize(name, age)
@name = name
@age = age
end
def describe
"#{@name} is #{@age}"
end
end
[Pet.new("Rex", 3), Pet.new("Tilly", 7)].each { |pet| puts pet.describe } A plain variable inside a method vanishes at its end, but an instance variable stays with the object.
guess first
Each piggy bank keeps its own coins. What shows?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class PiggyBank
def initialize(coins)
@coins = coins
end
def add(amount)
@coins += amount
end
end
mine = PiggyBank.new(5)
p [mine.add(3), mine.add(1), PiggyBank.new(5).add(1)]
your turn
Your turn. Create a game character.
Give your hero a name and a number of lives, then press run.
fix it
The bike has forgotten its name. Can you fix it?
- The name is missing, so
@namemust benil. Where should it get its value? - Line 3 stores the name in a plain variable, which vanishes at the end of
initialize. - Change line 3 to @name = name, then press run.
nailed it
your objects remember who they are. :D
.newpasses its arguments on toinitialize.- Instance variables start with
@and belong to one object. - Every method in the class can use them.
new words in your collection
- initialize
- instance variable
This lesson isn’t saved. A free account remembers every lesson you finish.