Journal Archives About Books Talks
journal

Three underused Ruby Array methods

When I first dove into Ruby, its powerful Enumerable module became my new hammer. I found a way to shoehorn most problems into map, each, inject, and the usual suspects. I was slow to discover some succinct idioms made possible by a few of Array's lesser known methods — idioms you only discover by digging through Other People's Code.

*

The join method is a common way to build a comma-delimited string:

[1,2,3].join(', ')
=> "1, 2, 3"

You could also build the same string using the * method:

[1,2,3] * ', '
=> "1, 2, 3"

If you use an integer as an argument, you can concatenate the array n times:

[1,2,3] * 3
=> [1, 2, 3, 1, 2, 3, 1, 2, 3]

|

Given Ruby's ultra intuitive support for combining arrays using +, it's common to see something like this:

([1,2,3] + [3,4,5]).uniq
=> [1, 2, 3, 4, 5]

The | method is a more idiomatic way find the union between two Arrays.

[1,2,3] | [3,4,5]
=> [1, 2, 3, 4, 5]

&

Ever writtenstumbled across something like this?

[1,2,3].select {|i| [2,3,4].include?(i) }
=> [2, 3]

The & method is an easier way to return the intersection between two Arrays.

[1,2,3] & [2,3,4]
=> [2, 3]

Bonus: *=, |= and &=

As an added bonus, you can modify an array variable in place using *=, |=, or &=.

a = [1,2,3]
a |= [2,3,4]
=> [1, 2, 3, 4]

|, &, |=, and &= also work for another underused Ruby feature: Set.

# Posted on