Nine Array Methods in Ruby Programming and their Differences
Nowadays, data handling is a big responsibility for every web and mobile application. Arrays make the process easier and it can handle any list of data. Once you have data in an array, you can easily sort it, remove duplicates, change its order to either ascending or descending and many more.
In Ruby programming, there are many methods for Array object i.e. Map, Collect, Select, Reject, Each, Inject, Reduce, Detect and Find. Most of the Ruby on Rails developers uses these methods in their web applications.
In this blog, we have outlined the difference between all the methods.Let’s have a look at them to choose the one which is best suitable for your requirement.
The map method takes each element from the array and evaluates
given block on it. Output will be in the form of an array containing evaluated results without changing the original array.
If you want to modify the original array by replacing the output array elements with the original array elements then you can use the map! method.
There is no difference between collect and map method both methods work same. Similarly map! and collect! methods are also same.
The select method takes each element from the array and evaluates given block on it. If block or statement evaluates to true the original elements gets added into the output array. In this case output array and original array are different. If you want to replace the original array to the output array, you can use select! Method.
The reject method is exactly opposite to the select method. It will take each element of the array in the block to evaluate. The output array will consist of all the elements in the original array for which block evaluates to false. The reject! method is also opposite to the select! method.
The each method will iterate over array taking each element from it for evaluation. It will return the original array, but not evaluated one. Now, it depends on you what kind of operation you want to perform in the block.
The inject method takes two arguments, one as an accumulator and other as each element in the array. Accumulator accumulates the evaluated values. This returns the final value of the accumulator as a result. The initial value of the accumulator can be defined if not define it takes the first element of the array as initial value.
Reduce method is similar to the inject method.
The detect method is similar to the select method, but the only difference is its output. The detect method also evaluates a block for each element of the array, but returns the first element in the array for which the block evaluates to true or statement in the block evaluates to true.
Find method is similar to Detect method.