Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Iterators in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 440
    Comment on it

    Iterators are used to iterate over each element of a collection or array one by one. In ruby there are different types of iterators. Here we are going to discuss over each and collect.

    1. each:

    It iterates over each element of the array or collection and each time the member is stored in a local variable and you can access it within that loop. There must be a block associated with the each loop.

    Example:
    
    arr = [11, 22, 33, 44, 55]
    arr.each do |member|
      puts "This is number: #{member}"
    end
    
    ## Output will be =>
    This is number: 11
    This is number: 22
    This is number: 33
    This is number: 44
    This is number: 55
    
    Thus here the iterator is running on the array and each time the member gets stored in the member variable "member" and is accessed inside the each loop.

    If you want to access the index also, you need to use each_with_index iterator, it also stores the index number of the member along with the member

    Example:
    
    arr = [11, 22, 33, 44, 55]
    arr.each_with_index do |member, index|
      puts "index is #{index} || number is #{member}"
    end
    
    ## Output will be =>
    index is 0 || number is 11
    index is 1 || number is 22
    index is 2 || number is 33
    index is 3 || number is 44
    index is 4 || number is 55

    2. collect:

    collect iterator returns all the members of a collection. It is not neccessary to use the block with it. You can either use block with it or not. If you want to have some modifications in each of the element of the collection, collect is best to use.

    
    Example:
    arr = [11, 22, 33, 44, 55]
    b = arr.collect{|a| a+1}
    
    ## Output will be =>
    [12, 23, 34, 45, 56]

    In the above example we have added one to each element of the array and stored the array in another variable.

    Hope you liked it.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: