Just Another Ruby Idiom
There's great resources on the web for learning Ruby and the "Ruby Way", notably Yehuda Katz's great Better Ruby Idioms.
We've all heard of the ||= operator, every Ruby guide ever produced goes to lengths to explain it, but the less common |= is what I wanted to have a natter about.
If you've ever found yourself doing something like:
klasses.each do |c| unless student.klasses.include? c student.klasses << c end end
..then you're mental. But it is a common problem when you have a has_many or has_and_belongs_to_many association and you want to avoid duplicate objects. Some might resort to:
student.klasses = (student.klasses + klasses).uniq
student.klasses |= klasses
As you can see, like it's assignment operator counterparts ||=, +=, -=, *=, etc, it expands to
student.klasses = student.klasses | klasses
It's possibly less readable than alternatives but it's nice and terse, and once you're using it regularly and all over the place you won't think twice. Enjoy.