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 |
|
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 |
|
The other is union, which concatenates the two arrays but removes duplicates:
1 2 |
|
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 |
|
The final trick I learned lets you autogenerate an array of a range of numbers. To whit:
1
|
|