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.
$ irb
2.2.2 :001 > numbers = [1, 2, 3, 4, 5]
=> [1, 2, 3, 4, 5]Here we assign an array of numbers to a variable.
2.2.2 :002 > numbers.find { |number| number > 2 }
=> 3The 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.
2.2.2 :003 > numbers.find_all { |number| number > 2 }
=> [3, 4, 5]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.
2.2.2 :004 > numbers.reject { |number| number > 2 }
=> [1, 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.
2.2.2 :005 > numbers.partition { |number| number > 2 }
=> [[3, 4, 5], [1, 2]]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.
2.2.2 :006 > strings = ["Ruby", "is", "so", "cool"]
=> ["Ruby", "is", "so", "cool"]Here we create an array of string values.
2.2.2 :007 > strings.find { |string| string.length > 2 }
=> "Ruby"This finds the first string with a length greater than two characters.
2.2.2 :008 > strings.find_all { |string| string.length > 2 }
=> ["Ruby", "cool"]This finds all strings with a length greater than two characters.
2.2.2 :009 > strings.reject { |string| string.length > 2 }
=> ["is", "so"]This rejects any string with a length greater than two characters.
2.2.2 :010 > strings.partition { |string| string.length > 2 }
=> [["Ruby", "cool"], ["is", "so"]]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.
2.2.2 :011 > exit
$As always, typing exit by itself exits irb, and returns us to the system prompt.