Loops and Iteration in Ruby
Going through 2 weeks of bootcamp I can’t iterate enough how important iterations and loops are. It is one skill I believe has helped me problem solve above average. On that note, I would like to teach looping through arrays like I am talking to my former non-techie self.
What is iterations? It is the idea of running a same action to each object of the group.
num_array = [1, 2, 3, 4, 5]
num_array.each |num| puts num * 2 end
The result is a follows
Lets break that down. What happened? I have a array called num_array that contains the numbers 1, 2, 3, 4, and 5. I ran the each method to the array.
I chose to use the each method because I think it is one of the most commonly used iterators and one that as a developer should know. The each method is basically pulling out each individual number 1 at a time and displaying the result of the number multiplied by 2.
The results are not stored because I used puts. The returned value is nil in this case.
Notable iteration methods
map, each, each_with_index, inject, and select
This of course is not the full list of iteration methods, but one’s that I find myself using frequently. If you have any questions feel free to contact me @johnmoon6. Follow me on Github – jmoon90.
If you want to read more about iterations I recommend you check Alan Skorkin’s out.