ruby · level 2 · unit 3 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
cuts a string into an array. join glues it back.
Lots of real data arrives as one long string, like "eggs,milk,bread". .split(",") cuts it wherever it finds the , here a comma, and hands back an array of the pieces.
.split with nothing in the brackets cuts at spaces and skips any extra ones, which is perfect for the words in a sentence.
.join goes the other way. It glues an array's items into one string, with whatever you give it placed between them.
line = "eggs,milk,bread"
items = line.split(",")
p items
puts items.join(" and ")
words = " the quick brown fox ".split
p words
puts words.map { |word| word.capitalize }.join(" ") .capitalize makes the first letter a capital and the rest small.
guess first
Split, count, join. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
row = "Amy,12,blue"
parts = row.split(",")
puts parts.length
puts parts.join("-")
your turn
Your turn. Tidy a shopping list.
Type a few things to buy in the blank, separated by commas, then press run to see them as a neat list.
fix it
Four words, but it counts one. Can you fix it?
- The program counts one word. Which separator is
.splitlooking for? - There are no commas in the sentence, so nothing gets cut. The words are separated by spaces.
- Change split(",") to split, with nothing in the brackets, then press run.
nailed it
you can cut text up and glue it back. :D
.split(",")cuts a string into an array at each separator..splitwith no argument cuts at spaces..join(", ")glues an array back into one string.
new words in your collection
- split
- separator
This lesson isn’t saved. A free account remembers every lesson you finish.