5 things you can do with a Ruby array in one line (PLUS A FREE BONUS!!)

March 23, 2007

Coming from a Java background, I’ve found arrays to be very “rigid”. And by rigid I mean they sort of suck. However, Ruby makes arrays flexible and a blast to work with. Let’s show by example rather than have me ranting about it. First, we assume we have an array with 100 random integers between 0 and 99. I would show you how to do this but typing the append symbol breaks wordpress (grr).

1. Summing elements: This is a fairly common task. We’ll use Ruby’s inject method to sum all the items in the array and then print out the sum:

puts my_array.inject(0){|sum,item| sum + item}

2. Double every item: This is a class of problem where we want to preform an operation on every element of the array. Again, this is fairly simple using Ruby’s map method. Think of performing a “mapping” from the first array to the second based on the function in the block. Keep in mind, this will return a new array and will NOT effect the original array. If we want to do a destructive map (change the initial array) we would use map!. This is a common convention in Ruby:

my_array.map{|item| item*2 }

3. Finding all items that meet your criteria: If you want to collect all the values in the array that meet some criteria, we can do this using the (duh) find_all method. Again, this will return an array. The code below finds all items that are multiple’s of three :

my_array.find_all{|item| item % 3 == 0 }

4. Combine techniques: Let’s now say we want to find the sume of all elements in our array that are multiples of 3. Ruby to the rescue! This is very simple because we can chain methods together gracefully in Ruby. Check it out:

my_array.find_all{|item| item % 3 == 0 }.inject(0){|sum,item| sum + item }

5. Sorting: We can sort items in an array quite easily. Below, I will show the standard sort and then a sort based on the negative value of the number. Both are so simple, my head just exploded:

my_array.sort
my_array.sort_by{|item| item*-1}

Bonus!: As a bonus for all of you lovely readers, I will show you how to filter an array of strings based on a pattern. Let’s say you have huge array of strings and you want to collect any string that looks like this: 555-555-5555. Assume that the 5’s could be any digit (we are looking for phone numbers). First, we create a regular expression that expresses this phone number jazz: /\d{3}-\d{3}-\d{4}/ (I’m not going into regular expressions here, but you can google them if you want to know more). Now, we simply use the find_all method discussed earlier combined with Ruby’s slick =~ operator. This will tell us if there is our string matches the regular expression. So, without further ado, here is how you would filter an array to find strings that contain phone numbers:

my_array.find_all{|item| item =~ /\d{3}-\d{3}-\d{4}/ }

Stay tuned, more Ruby goodness to come!

Don’t be shy, check out everything you can do with Ruby’s Array

About these ads

8 Responses to “5 things you can do with a Ruby array in one line (PLUS A FREE BONUS!!)”

  1. mike Says:

    Thanks!

  2. Ola Bini Says:

    Notice that your last example is actually not the best way to do it. First, your regexp is not optimal, and you shouldn’t use find_all for this:

    my_array.grep /(\d{3}-){2}\d{4}/

    Cheers

  3. drewolson Says:

    Ola –

    Very true. I learn more and more about the languages new features every day and I’d definitely a few of these examples differently today.

  4. coban Says:

    how about performing Swartzain transform in ruby.

    I use it all the time in perl, it is even cleaner and easier to read in ruby.

  5. poster Says:

    one of the most comprehensive writeups (on a little but very important thing) i’ve ever seen. thank you! :-)


  6. The Enumerable method sort_by is a built-in Schwartzian Transform in Ruby.

    http://www.ruby-doc.org/core/classes/Enumerable.html

  7. Evan Anderson Says:

    Noticed you used the inject and find_all methods in your examples, yet I see no documentation on them in the Array class. Do you know where these are coming from?

  8. Evan Anderson Says:

    Ah I’ve found them, they are from the Enumerable class.


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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: