Learn Ruby the Hard Way – Exercise 32 Loops and Arrays

Here is my work for Exercise 32.

Exercise 32 code
Exercise 32 code
Exercise 32 output
Exercise 32 output

Study Drills
1. Take a look at how you used (0..5) in the last for-loop. Look up Ruby’s “range operator” (.. and ...) online to see what it does.
Ruby’s range operator is used to loop through a collection of integers. (..) is inclusive of the first and last element, (…) is exclusive of the last element.

(first_number..last_number).each do |number|
puts number
end

The above code will print the range from the first_number to the last_number.

2. Change the first for number in the_count to be a more typical .each style loop like the others.

Rewriting the for.. in ... loop.
Rewriting the for.. in … loop.

3. Find the Ruby documentation on arrays and read about them. What other operations can you do besides the push function? Try <<, which is the same as push but is an operator. fruits << x is the same as fruits.push(x).
Here is the Ruby documentation on arrays. You can also sort arrays, reverse arrays, replace specific elements.. etc. The <<  append operation pushes the given object on to the end of the array. We can use fruits.push(new_fruit) to add new fruit elements to our fruits array. I added the code below to the end of the script.

Adding fruits and printing the list again.
Adding fruits and printing the list again.
Fruits!
Fruits!

Summary
This exercise uses arrays and loops (.each, for element in array) to make arrays and print their contents. You can loop through integers using (first_number..last_number) and (first_number…last_number), two dots are for inclusive loops (first and last element) while the three dots are for exclusive loops (exclusive of the last integer indicated). Coming from JavaScript (and always using the for loop), I’m happy to find the .each method even easier to use!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s