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.
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.
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).
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?)
“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.
Here we create a new array, this one filled with strings, and assign it to a new variable.
This block calls reverse
on each string in the array, and prints the result.
This block prints the length of each string in the array.
As always, type exit
when you’re ready to return to the system prompt.