Saving Multiple Values on Ruby


Saving Multiple Values

Let's say we want to save a range of numbers in a variable. How would we do this? A variable can only hold a single value, right?

In Ruby, we can pack multiple values into a single variable using an array. An array is just a list of items between square brackets, like so: [1, 2, 3, 4]. The items don't have to be in order—you can just as easily have [10, 31, 19, 400].

Create a variable called my_array and set it equal to the numbers 1 through 5, inclusive, in order.



Without a clear idea of which lesson you are on, I'm just going to go out on a limb and suggest something literal...

my_array = [ 1, 2, 3, 4, 5 ]

Please tell us which module and lesson number. Thank you.


thank you. It worked. :grinning: This lesson's # is: ("Loops & Iterators" - 10. Saving Multiple Values.)

I thought I need to do something like my_array = [1...5] :unamused:


In lesson 13 we learn about .times, which is a useful method for counting.

my_array = []
5.times { |i| my_array.push i+1 }
print my_array
[1, 2, 3, 4, 5]nil

In the block we have a parameter, i, which is an internal iterator starting at 0. With each count on the .times method parameter, 5, the value of i+1 is pushed to the array (so we start the sequence at 1) and Ruby increments the iterator for the next pass. Notice here that control is outside of the block. i will keep clicking away for as long as .times asks it to.

Anyway, I'm not sure this example comes up in a lesson, but it's interesting all the same.