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.
That's a pretty cool tip, Avdi.
I realize that this is old, but this is awesome.
Thanks!