Chapter 6 - Block return values
Exercise 2: IRB session
Here’s the output you’ll see when you type those expressions into irb
. We’ve also added some notes about what the results mean.
Here we assign an array of numbers to a variable.
The find
method is just like find_all
, except that it returns only the first array element for which the block returns true
. The first element that’s greater than 2
is, of course, 3
.
And as we saw before, find_all
returns an array of all the elements for which the block returns true
. 3
, 4
, and 5
are all greater than 2
.
The reject
method is the opposite of find_all
; it returns an array of all elements for which the block returns false
(rejecting the elements for which it returns true
). 3
, 4
, and 5
are greater than 2
, and so they were rejected.
The partition
method returns two arrays, one with all the values for which the block returned true
, and a second with the values for which the block returned false
.
Here we create an array of string values.
This finds the first string with a length
greater than two characters.
This finds all strings with a length
greater than two characters.
This rejects any string with a length greater than two characters.
This partitions the array into two arrays: one with all the strings longer than two characters, and a second array with strings that are not.
As always, typing exit
by itself exits irb
, and returns us to the system prompt.