Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Iterators and its usage in ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 834
    Comment on it

    In Ruby, iterators are methods basically used by the collections. Collections are a set of objects. Hashes & Arrays are the example of collections. Iteration is a process by which we can get or set the elements in collections. We will discuss some of them which is give below...

     

    each: The each iterator is used a block to get all the elements of collections(array or hash).

    #Syntax: 
    collection.each do |v|
    #Block
       #Statement..1...
       #Statement..2...
    end

     

    In above code, executes "Statement" for each element of an array or a hash.

    arr = [5,6,7,8,10]
    arr.each do |v|
       puts v
    end
    
    #Output:
    5
    6
    7
    8
    10

     

    Collect: This iterator gives all the elements of a collection. There is no need to associate a block to get value from collection.

    #Syntax:
    collection = arr.collect
    
    v1 = [5,6,7,8,9,10]
    v2 = Array.new
    v2 = v1.collect{ |v| v }
    puts v2
    
    #Output:
    5
    6
    7
    8
    10

     

    The above script is copying the one array to other array.
    Note: To copy an array use clone method in ruby

 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: