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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 160
    Comment on it

    Enumerable Methods in Ruby

    Ruby has a list of enumerable methods or we can say enumerators that have specific functionalities which can be applied on various collections like array ,hashes etc

    • Map
    • Select
    • Each
    • Collect

    Map

    Map method allows us to iterate through a collection for example array and perform a specific action on all the elements of that array and then again returns an array

    Example : 

    a = [1,2,3,4]
    
    a.map do |b|
    
     b*2
    
    end
    
    # now the array returned would be a = [2,4,6,8]

     

    Select

    Select method helps us to select desired elements from a collection and then again returns a collection out of it.

    Example:

    a = [1,2,3,4,5,6,7,8,9]
    
    a.select |b|
    
     b >= 2&& b <= 5
    
    end
    
    #The output would be a = [2,3,4,5]

     Each

    The each method returns all the elements of the collection then be it array or hash.

    Example

    a = ["one,"two","three"]
    
    a.each do |b|
    
     puts b
    
    end
    
    #The output would be a =["one,"two","three"]

    Collect

    Collect method allows us to iterate through all the elements of the collection and is similar to map method.

    Example

    a = [2,4,6,8]
    
    b = a.collect{|x| 2*x}
    
    puts b
    # The output would be b = [4,8,12,16]

     

 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: