Ruby Programming Tutorial - Lesson 12 - Loops in Ruby :: EACH Loop

in ruby •  7 years ago  (edited)

Capture.JPG

Each loop, in other languages its also called For-each loop

Its also used to iterate through values..
Lets take an example to learn more about it,

# Each loop is used to do something repeatedly 


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

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

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


(0..10).each do |i|

This is start of loop, see the Syntax ...
Iterative statement comes first, or the values through which we want to iterate ..
with "." comes next and we use "each" keyword .. next comes the do keyword..
"|i|" this is temporary variable. which will store the current value of iteration ...

lets take another similar example..
In this Example we are using each loop with Case statement which we learned in previous tutorial..
We are free to use different programming techniques we learned so far, in our programs

# Create a Program that converts Decimal numbers into English Words

(0..4).each do |i|
    case i
    when 0
    puts "Zero"
    when 1
    puts 'One'
    when 2
    puts 'Two'
    when 3
    puts 'Three'
    when 4
    puts 'Four'
    end
end

Capture.JPG

Now you have learned on how to use "each loop" to do iteration through values...

Once we learn Arrays .. we will see more uses of this amazing loop.
it can come very handy when dealing with huge amount of data ...

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

essential

You got a 4.35% upvote from @ipromote courtesy of @bilal-haider!
If you believe this post is spam or abuse, please report it to our Discord #abuse channel.

If you want to support our Curation Digest or our Spam & Abuse prevention efforts, please vote @themarkymark as witness.