Chapter 5 - Arrays and Blocks

Exercise 3: 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.

2.2.2 :001 > numbers = [3, 29, 5, 12, 18]
=> [3, 29, 5, 12, 18]

Nothing too fancy here; this just creates an array of numbers and stores a reference to the array in a variable. Make sure you use whole numbers, though, or the next expression won’t work.

As always, the result of an assignment expression is the value assigned, which is why IRB prints => [3, 29, 5, 12, 18] afterward.

2.2.2 :002 > numbers.each { |number| puts number * number }
9
841
25
144
324
=> [3, 29, 5, 12, 18]

This multiplies each number in the array by itself (squares it), and prints the result.

The return value of the each method is the array that you called it on, so IRB again prints => [3, 29, 5, 12, 18] after this method call (and the following ones).

2.2.2 :003 > numbers.each { |number| puts number.odd? }
true
true
true
false
false
=> [3, 29, 5, 12, 18]

This calls the odd? method on each number in the array, and prints the result. The odd? method returns true if the number you called it on is odd, and false if the number is even. (There’s also an even? method that does the opposite; why not try it out now?)

2.2.2 :004 > numbers.each { |number| puts "$" * number }
$$$
$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
$$$$$
$$$$$$$$$$$$
$$$$$$$$$$$$$$$$$$
=> [3, 29, 5, 12, 18]

“Multiplying” a string by a number returns that string, repeated that number of times. (So, "ab" * 3 returns "ababab".) The above call to each results in a kind of primitive bar chart.

2.2.2 :005 > strings = ["I", "ma", "a", "ybuR", "retsam"]
=> ["I", "ma", "a", "ybuR", "retsam"]

Here we create a new array, this one filled with strings, and assign it to a new variable.

2.2.2 :006 > strings.each { |string| puts string.reverse }
I
am
a
Ruby
master
=> ["I", "ma", "a", "ybuR", "retsam"]

This block calls reverse on each string in the array, and prints the result.

2.2.2 :007 > strings.each { |string| puts string.length }
1
2
1
4
6
=> ["I", "ma", "a", "ybuR", "retsam"]

This block prints the length of each string in the array.

2.2.2 :008 > exit

As always, type exit when you’re ready to return to the system prompt.