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.

Published by Avdi Grimm

3 Comments

  1. That's a pretty cool tip, Avdi.

    Reply
  2. I realize that this is old, but this is awesome.

    Reply

Leave a Reply

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