Comparing Adjacent Elements in Ruby

submited by
Style Pass
2023-03-18 15:30:03

Shout-Out to CodinGame… it’s perhaps the best place to practice coding puzzles, learn more about your favorite languages, and, optionally, learn some pretty cool game AI specific techniques. One of the greatest features they have is the ability to see other’s solutions to a problem after you’ve completed yours, complete with full comments from other users and rankings for the best solutions per-language to each challenge. This is a great way to discover new language features or algorithmic approaches you may not be familiar with. You can also follow me there!

While exploring some coding puzzles there I found a couple neat tricks for comparing adjacent elements in Ruby that I’d like to share.

a straight-forward solution in Ruby might be to loop through the list, calcuate the difference between adjacent digits, and remember the smallest difference.

After reviewing the top-ranked solutions on CodinGame however, I discovered 2 new Ruby solutions that are much more elegant. One using the each_cons method, the other using a combination of zip and rotate.

Leave a Comment