Join and Inject methods for arrays in ruby
Join method is used to combine all array elements into one string.
With the help of join method we can combine a lot of strings present in an array into one single string.
Join method can also be used to insert something between strings
Example 1:
In the below screenshot we can clearly see what join method did. It joined both the strings.
![](http://findnerd.s3.amazonaws.com/imagedata/5655/5655.png)
We can also insert something between two strings with the help of join method like this.
Now, Use the Array#join method (the argument to join is what to insert between the strings - in this case a space) :@arr.join(", ")
Example 2:
![](http://findnerd.s3.amazonaws.com/imagedata/5656/5656.png)
Whereas, Inject method combines all elements of enum by applying a binary operation, specified by a block or a symbol that names a method or operator.
If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element. If you specify a symbol instead, then each element in the collection will be passed to the named method of memo. In either case, the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value for the method.
If you do not explicitly specify an initial value for memo, then uses the first element of collection is used as the initial value of memo.
Examples:
![](http://findnerd.s3.amazonaws.com/imagedata/5657/5657.png)
0 Comment(s)