3 ms·
I don't quite get the distinction in your first item: What's the difference between `a = (a || b)` and `a || (a = b)` ?
by greenpeas 4y ago
I don't quite get the distinction in your first item:
What's the difference between `a = (a || b)` and `a || (a = b)` ?
- Jabbles 4y agoThe rabbithole is here: https://stackoverflow.com/q/995593 https://stackoverflow.com/q/995593
- greenpeas 4y agowow, thanks. I worked with ruby for more than 5 years, and `||=` never surprised me. TLDR On the distinction between `a = (a || b)` and `a || (a = b)`: * There is no difference when `a` and `b` are local variables (unless `a` is undefined, but that's an edge case) * The distinction manifests when `a=` is a method. (It could be a `[]=` or some attr_accessor). Then `a = (a || b)` always invokes `a=`, whereas `a || (a = b)` only invokes `a=` when `a` is falsey. In essence however, `a ||= b` respects the intuitive definition that it sets `a` to `b` if and only if `a` is falsey.
- cycomachead 4y agoYeah, it's not usually an issue in practice. But I do see students get confused trying things out...and it's likely because learning in an interpreter doesn't often look like "real" code does.