Blog posts for Ruby, Ruby on rails and Linux.

Go back to all blogs

Combine two arrays into single and remove the duplicate with one single expression in ruby.

Kapil Raj Nakhwa2013-Nov- 1
Hi Guys, 
So There are many many times in a single day when you are working in ruby and you might need to perform operations in array. And you might also need to combine two arrays into a single one.
Here is the command we usually go for 

a=[0,1,2,3,4]
b = [2,3,4,5,6,7,8,9,0]
c = a+b 
But the problem with this is the fact that the resulting array "c" would still have duplicate elements. And in most of the case you might need to remove the duplicate elements. 
So we end up calling uniq in the array 'c'.
c.uniq
So here is a cool tip you can use to perform the above thing in a single shortcut command. 


c = a | b
=> [0,1,2,3,4,5,6,7,8,9]

This is an awesome shortcut to use in your daily ruby development. 

Tags: ruby,arrays,combine,trick

Go back to all blogs
Never miss a post on new ruby and rails tips