ruby · level 2 · unit 6 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A class is a recipe for making your own objects.
The class of a value tells you its kind, like String or Integer. Now you can make your own. Write class, a name in , the methods, then end. The class is a recipe: it does nothing until you use it.
Robot.new follows the recipe and hands you a new . Each object is an of its class, so calling Robot.new twice gives two separate robots. Every robot can use the methods written inside class Robot.
class Robot
def greet
"Beep! Hello."
end
end
robo = Robot.new
puts robo.greet
p robo.class
puts Robot.new.greet Class names start with a capital letter, which is how Ruby tells them apart from variables.
guess first
Two kittens from one recipe. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Kitten
def sound
"Mew"
end
end
tom = Kitten.new
kit = Kitten.new
puts tom.sound + " " + kit.sound
p kit.class
your turn
Your turn. Build a toy.
Give your toy class a name in CamelCase. Use exactly the same name in both blanks, then press run.
fix it
Ruby will not accept this class name. Can you fix it?
- Read the error. Ruby cannot read this code at all. How must a class name start?
- Class names start with a capital letter and use CamelCase, not snake_case.
- Change pet_shop to PetShop on line 1 and line 6, then press run.
nailed it
you designed your own kind of value. :D
- A class is a recipe.
.newmakes an object from it. - Each object is an instance of its class.
- Class names use CamelCase, like
PetShop.
new words in your collection
- CamelCase
- object
- instance
This lesson isn’t saved. A free account remembers every lesson you finish.