ruby · level 1 · unit 3 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Methods are tricks that every string knows.
A is a command that belongs to a value. Write the value, a dot, then the method's name. You met one already: .chomp. Here are some more.
counts every letter, space and symbol. .upcase shouts in capitals and .downcase whispers in small letters. .strip trims spaces off both ends.
.sub swaps the first match for new text, so "banana".sub("a", "o") gives bonana. swaps every match, giving bonono. The box stays the same unless you store the result.
word = " Hello "
puts word.strip
puts word.strip.length
puts word.upcase
puts "banana".gsub("a", "o") You can chain methods: word.strip.length trims first, then counts what is left.
guess first
How long is this string?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
puts "Hi there".length
your turn
Your turn. Shout across the playground.
Type something you would shout across a playground, in small letters. Run it to hear it in capitals, then see how long it is.
fix it
This should shout HELP, but it whispers. Fix it!
- Line 2 makes a shouty copy of the word. Where does that copy go?
- A method hands back a new string. The box stays the same unless you store the result.
- Change line 2 to word = word.upcase, then press run.
nailed it
you taught your strings new tricks. :D
- A method is a command after a dot.
.upcase,.downcaseand.stripmake new strings.- Store the result if you want to keep it.
new words in your collection
- method
- length
- gsub
This lesson isn’t saved. A free account remembers every lesson you finish.