Fun little array method I found helpful

August 3, 2007

First, sorry for the lack of posting over the past month. Things have been fairly crazy/interesting on the job front. More on that later.

For now, I want to share a nifty little method I put together (I’m probably not the first one) to deal with a situation I recently encountered. I had a bunch of data in an array and I wanted to compare each element with the elements next to it, one at a time, and find any place where the difference between the numbers was more than 10. Here’s what I added to the Array class to accomplish this task:

Little-bitty code snippet

This allows me to perform the function I wanted simply by doing this:

my_array.adjacent_pairs.inject(0){|count,(i1,i2)| count + ((i1-i2).abs > 10 ? 1 : 0)}

Nice and easy. Ruby has made it a breeze for me the solve problems like this in simple, understandable ways without extra fluff.

Update:
It appears ruby is even smarter than I imagined; this functionality is already present!

require 'enumerable'
my_array.each_cons(2){|a,b| #do something with a and b }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s