Hi, welcome to Word of Mike, my little corner of the internet. I am a Software/Web Developer working in North Yorkshire. I mainly write about programming but my other passion is politics so beware. (click to hide)

2013-03-08 21:27:49 UTC

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

Which is alright. But why not do *drumroll please*:

student.klasses |= klasses

As you can see, like it's assignment operator counterparts ||=, +=, -=, *=, etc, it expands to

student.klasses = student.klasses | klasses
, which ORs the two arrays together, therefore avoiding duplicates of course..

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.