Ruby Programming Tutorial - Lesson 11 - Loops in Ruby :: For...in Loop

By @bilal-haider3/3/2018ruby

Capture.JPG

For...in loop

In this article, we are going to learn about "For" loop its well known loop, and used in almost every programming language. Here is how it works in Ruby

# For loop is used to do something repeatedly 


for i in 0..5
   puts "This is Value of i: #{i} "
end

In this example we are printing a message for 6 times, which is the loop starts at 0 and ends at 5 ..
Prints message containing the value of "i" ..

Lets take another example.
and use a conditional statement inside for...in loop.


for i in 0..10
   if i > 2 then
      break
   end
   puts "Value of 'I' is: #{i}"
end

Note in this example. we have created a loop that had to print a message 11 times.. because
we specifed, it to go from 0 to 10 ..
but it prints only 3 lines.. that because of conditional statement and the "break" statement.

Break statement is used to break a loop at any point of time ...

now the fun example :)

Give vote up on bilal's latest 11 posts :) only if Steem power is greater than 10,000

steem_power         = 50000
account_name        = "bilal-haider"
vote_on_all_posts   = true



for i in 0..10
   if vote_on_all_posts && account_name == "bilal-haider" && steem_power >= 10000 then
      puts "Vote given for post #{i}"
   end
end

In this lecture you guys have learned on how to use for .. in loop. and also learned how to write break statement
, combining the knowledge of writing conditional statements with loops :)

You guys are becoming an awesome ruby programmer as time is progressing.

24

comments