Treating Arrays as Sets

Reading through the Rake source code the other day (a pastime I highly recommend), I was reminded of a technique I don’t use often enough:

my_array = [:foo, :bar, :baz]
my_array |= [:baz, :buz] # => [:foo, :bar, :baz, :buz]

Note that’s a single pipe before the equals sign.

The code above adds only unique elements to the array; duplicates are ignored. Ruby Arrays actually implement a small collection of set operations with the &, | operators. Of course, for serious set needs you can use Ruby’s Set, but |= is handy for uniquely appending to an array.

3 comments

Leave a Reply to Charles Strahan Cancel reply

Your email address will not be published. Required fields are marked *