Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Array operations in ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 529
    Comment on it

    In our regular programming life, we always come in to situation where we need to pick few elements from array, remove them or insert some elements into them. In ruby there are methods available for such operations. Some of them are:

    1) Select:

    Select is used to select few elements from array based on some condition. Suppose you want to find even numbers from an array, you can do that like this:

    > a = [1,3,4,6,7]
    > a.select {|n| n%2==0}
    ## It will give output an array containing the even numbers:
    => [4, 6]

    2) Reject:

    Reject is opposite to the select. it is used to fetch the elements that do not satisfy a specific condition. As in previous example, if we use the reject in place of select. It will give all the elements except those that are even.

    > a = [1,3,4,6,7]
    > a.reject {|n| n%2==0}
    ## It will give output an array containing the odd numbers:
    => [1, 3, 7]

    3) Collect:

    Collect also returns an array, but it is basically used if we want to iterate over each element of array and perform an operation on each element. Like suppose we want to add 2 to each element of our array, we will do like this:

    > a = [1,3,4,6,7]
    > a.collect {|n| n+2}
    ## It will give output an array by adding 2 to each element of the input array:
    => [3, 5, 6, 8, 9] 
    

     

    4) Inject:

    Inject is used if we want some additional operation in the array. It gives us another variable that can be used in the block, this is known as accumulator, it is actually the result of the condition mentioned in the block and after each iteration it stores the value of the previous result. , you can  see in the example as:

    > a = [1,2,3,4]
    a.inject {|acc,n| acc*2 + n}
    #=> It will give output
    => 26

    You can also pass the default value of accumulator in the inject

    > a = [1,2,3,4]
    a.inject(10) {|acc,n| acc*2 + n}
    #=> It will give output
    => 186

     

 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: