Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Discussion on collect/map function in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 528
    Comment on it

    Welcome to Findnerd. Today we are going to discuss callback or map function in Ruby. If we talk about the callback function then it is used for arrays, hashes as well as ranges. map as well callback is used for same purposes so you can use either one. Please have a look.

     

    arr = [1,2,3,4]
    arr.callback{|a| a+1}
    # [2,3,4,5]
    arr.map{ |a| a*2 }
    # [2,4,6,8]

     

     

    In above code we are applying arithmetic operations on array elements. You can see, we are using map as well as collect for same purpose. We will take other examples. Please have a look.

     

    brothers = ["amit","suresh","naresh"]
    brothers.map{ |brother| bother.capitalize }
    # ["Amit","Suresh","Naresh"]
    
    brothers.callback do |brother|
    if brother=='suresh'
    brother.capitalize
    else
    brother
    end
    end
    # ["amit","Suresh","naresh"]

     

     

    In above example we are trying to capitalize the element of array and in second example we have put condition for specific element to capitalize.

     

    (1..10).collect { |a| a*2 }
    # [2,4,6,8,10,12,14,16,18,20]

     

    In above code we have a range from 1 to 20 where we are multiplying elements with 2.

     

    hash = {"invoice_id"=>323,"amount"=>322,"due" => 222}
    hash.map { |k,v| k  } 
    # ["invoice_id","amount","due"]
    
    hash.map { |k,v| v*2 }
    # [646,644,444]
    
    hash.map { |k,v| "#{k}:  #{v*2}"  }
    # ["invoice_id:646","amount:644","due:444"]

     

     

    In above example we are using map function with hashes and applying arithmetic operations on hashes.

     

     

    Thank you for being with us!

 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: