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
• 343
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)

OR
OR
Register

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

• Hire
• Post Projects

### Post Projects

• All at 0 Cost ....
• Post Tech Job
• Select Best Bidder
• Track the Project
• Approve Work and Pay safely
• Browse Nerds
• Work
• Find Projects Find Projects
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
• Manage
• Company Company

### Manage Company

• All at 0 Cost ....
• Manage Company and Employee Profiles
• Company wide Employee Productivity Reports
• Knowledge Sharing and Collaboration Tools
• Get Sales Lead and Bid for Tech Projects
• Send Invoices and Receive Payment Safely
• Learn
• Nerd Digest Nerd Digest
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General
• Tech Q & A Tech Q & A
• UI Design and UX
• Software Engineering
View more...
View less...
• Marketing
• General