ruby · level 2 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
keeps the yeses. drops them.
.select runs a yes-or-no block on every item and keeps the items that get true. .reject is its mirror image: it drops the true items and keeps the rest. Both hand back a new array.
stops at the first item that gets true and hands back that one item, or nil if nothing matches. .count with a block counts the true answers.
On a hash, .select and .reject hand back a smaller hash, and the block gets the key and the value.
ages = [4, 12, 17, 30, 9]
p ages.select { |age| age >= 12 }
p ages.reject { |age| age >= 12 }
p ages.find { |age| age > 15 }
p ages.count { |age| age.even? } Write each block as a yes-or-no question, and these methods read like plain English.
guess first
Which snacks are cheap? Guess the output.
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
snacks = { crisps: 80, cake: 250, apple: 40 }
cheap = snacks.select { |snack, pence| pence < 100 }
p cheap.keys
your turn
Your turn. Find the long words.
Pick a number of letters, small enough that at least one word is longer. .select keeps the longer words and .find shows the first.
fix it
The cinema is counting the children. Can you fix it?
- Count the adults yourself. Three ages are 18 or over, but the program counts two.
.rejectdrops the items where the block saystrue, so it kept the children.- Change reject to select on line 2, then press run.
nailed it
you can filter any list now. :D
.selectkeeps the items whose block saystrue..rejectdrops them and keeps the rest..findgives the first match, ornil.
new words in your collection
- select
- reject
- find
This lesson isn’t saved. A free account remembers every lesson you finish.