Katie on Rails

On Internets and other things

Stupid Ruby Array Tricks

While checking out the Ruby katas, I came across a puzzle that involved comparing two arrays, and was on the verge of writing long, convoluted if statements when it occurred to me that any language as elegant as Ruby must have better ways of doing things. Indeed it does. For example:

Check to see if 2 arrays have any matches, in 3ish lines of code

1
2
3
array1=["Cookie Monster","Big Bird", "Grover"]
array2=["Snuffy","Cookie Monster", "Elmo"]
intersection=array1&array2

Intersection will equal all the correct responses, in this case, Cookie Monster. (From Stack Overflow)

This method has two cousins. One is difference, which lets you “subtract” items from array1 that are also in array2:

1
2
difference=array1-array2
difference= ["Big Bird", "Grover"] 

The other is union, which concatenates the two arrays but removes duplicates:

1
2
array | array2= 
["Cookie Monster", "Big Bird", "Grover", "Snuffy", "Elmo"]

Puttering about the Internet a litte bit, I also found this post in Japanese. I could read only the code, but it’s there that I discovered mass shuffling. For example,

1
2
array1<<"a horse"<< "a truck" = 
["Cookie Monster", "Big Bird", "Grover", "a horse", "a truck"]

The final trick I learned lets you autogenerate an array of a range of numbers. To whit:

1
[*1..10] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]