||=
It’s fitting that pipes equal looks like a duck, because I have been talking to one quite a bit lately trying to understand ||=‘s strange behavior.
For instance, the problem I am reviewing now I have the following method in a class instance:
Ok.
After first pass over I wonder how the heck am I shoveling into a hash? (I’m not)
Secondly, what kind of sorcery is ||= doing?? Let’s ask our bff, PRY.
Wait, what the what ?
roster [grade] ||= []
returns roster[grade] = [ ] , a key value pair. Ok! ... but how?
roster[grade] ||= []
roughly translates to
if defined? roster[grade] roster[grade] || roster[grade] = [] else roster[grade] = [] end
If the grade exists, then add the student to the array of student names.
If the grade doesn’t exist, create it with an empty array as the key, then add the student name to that array.
Cool!
The resources that helped me understand this use of ||=
https://www.tutorialspoint.com/ruby/ruby_operators.htm
http://www.rubyinside.com/what-rubys-double-pipe-or-equals-really-does-5488.html














