DEV Community

Discussion on: Mastering Ruby Arrays

Collapse
 
codeandclay profile image
Oliver

As well as concatinating an array with + you can use - to show you the difference.

[1,2,3,4,5] - [3,4,5] #[1, 2]
Enter fullscreen mode Exit fullscreen mode

& returns the intersection of two arrays. (Items that both arrays contain.)

[1,2,3,4,5] & [4,5,6,7] #[4, 5]
Enter fullscreen mode Exit fullscreen mode

| returns a union. (A combination of both arrays without duplicates.)

[1,2,3,4] | [1,2,3,5] #[1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Also, the constructor takes a block -- which can be handy.

Array.new(3) #[nil, nil, nil]

Array.new(3) { [*1..100].sample } #[24, 61, 76]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ericchapman profile image
Eric The Coder

Thanks a million, I just update the post! I did not even know the union and intersection exist! After 2 years of Ruby I am still impress how easy it is compare to other programming language.

Those are powerful and complex Array operators but Ruby make those so easy to use.

Collapse
 
codeandclay profile image
Oliver

Yes, handling strings and collections in Ruby is a breeze. Those methods are ones I use often so were off the top of my head.