ruby · level 1 · unit 7 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A method is a recipe card with a name on top.
You have used methods like upcase. Now you can make your own: a set of instructions wrapped up under one name. Write the recipe once, then cook it as often as you like, without copying a single line.
Start with , short for define, then the name. The lines underneath are the recipe, and end closes the card. Writing the card does not run it.
To the method, write its name on a line of its own, like cheer. Every line in the recipe then runs, top to bottom. Call it twice and it runs twice.
def cheer
puts "Go team!"
puts "You can do it!"
end
cheer
cheer Change the recipe and every call uses the new version.
guess first
Ruby reads top to bottom. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
cheer
def cheer
puts "Go team!"
end
your turn
Your turn. Write your own chant.
Pick a name for your method, in small letters, and type it in all three name blanks. Put any words you like between the quotes, then run it.
fix it
The dog never barks. Can you fix it?
- The method is written perfectly. But does anything ask it to run?
- Writing a method only makes the recipe card. You need to call it.
- Add a new last line that says bark, after the
end, then press run.
nailed it
you wrote your very own command. :D
- A method is a set of instructions with a name.
- Start it with
defand close it withend. - Call it by its name, after you define it.
new words in your collection
- def
- call
This lesson isn’t saved. A free account remembers every lesson you finish.