Close
Close

for and each loop in Ruby


If you are here, this means that you are going to be a coder soon. You will solve real-world computer problems, make your own programs, and a lot more. Yeah, sounds good!

Same as 'while', for is also a loop. Let's see an example to understand this.

marks = [78,98,50,37,45]
for m in marks
  puts m
end
Output
78
98
50
37
45

Just this and it's done. Let me explain you the code.
for m in marks - m is a variable which will go to every element in the array 'marks' and take its value.

So, in the first iteration, m will be the 1st element of the array.
In the second iteration, m will the be the 2nd element of the array and so on.

As you have seen above, in the first iteration, m is 78, in the second iteration, its 98, then 50 and so on.

for loop in ruby
Notice that we have to use end to end the for loop also.

Example of sum of marks

marks = [78,98,50,37,45]
sum = 0
for m in marks
  sum = sum+m
end
puts sum
Output
308

I hope that you got the code. If not, then let me explain a bit.
sum = 0 - We are taking any variable and assigning it an initial value of 0.
In the 1st iteration
m is 78. So, sum+m is 0+78. Now the sum is 78
In the 2nd iteration
m is 98. So, sum+m is 78+98. Now the sum is 176.
Similarly at last, sum is 308.
I hope it is clear now.

Do You Know ?

Table of 12 Add And you get table of 13
12 +1 13
24 +2 26
36 +3 39
48 +4 52
60 +5 65
72 +6 78
84 +7 91
96 +8 104
108 +9 117
120 +10 130

So, let's do it with the help of for loop.

table_12 = [12,24,36,48,60,72,84,96,108,120]
table_13 = []
z = 1
for i in table_12
  table_13.push(i+z) #using push to add an element in front of list
  z = z+1
end
puts "#{table_13}"
Output
[13, 26, 39, 52, 65, 78, 91, 104, 117, 130]

z = 1 - We have to add 1,2,3... respectively to each element. And that's what we are doing. Add 1 and then increase z by 1 for the next turn (z = z+1)
table_13.push() - push() is a function of array which adds an element in front of an array. So, (i+z) will add (12+1),(12+2),...(12+10) in their respective turns in the array.
By writing your codes, your mathematics is gonna be fun.

each


each is just like 'for' loop but with different syntax and in more Ruby style. Let's see an exapmle.

marks = [78,98,50,37,45]
marks.each do |m|
  puts m
end
Output
78
98
50
37
45

It is same as for m in marks. m will go to every element of the array marks and will take its value in each iteration. So, same as 'for', in the first iteration, 'm' is 78, in the second, 'm' is 98 and so on.

We can also use each and for on range. Let's see the example given below to understand this.

a = (1..5)
# using each
a.each do |m|
  puts m
end
# using for
for m in a
  puts m
end
Output
1
2
3
4
5
1
2
3
4
5

As you have seen in the previous example, we have used 'for' and 'each' on (1..5).

Knowing is not enough, we must apply. Willing is not enough, we must do.
-Bruce Lee


Ask Yours
Post Yours
Doubt? Ask question