3 ms·
That's not specific to 'unless' – it's the general postcondition style that's is derived from Ruby. Indeed, for single-line if statement bodies in Ruby, it's th
by matthewmacleod 11y ago
That's not specific to 'unless' – it's the general postcondition style that's is derived from Ruby. Indeed, for single-line if statement bodies in Ruby, it's the recommended style.
It fits the style of Ruby to try and cut down on syntax noise where it's not needed. Contrast:
save! if !record.persisted? && !record.invalid?
save! unless record.persisted? || record.invalid?
Though I do appreciate it's a bit unusual compared with most other languages – CoffeeScript does owe a lot to Ruby's syntax.
- untog 11y agoThat's not really the part of unless that bothers me - it's the order. Why not do: if !record.persisted? && !record.invalid? save! or: unless record.persisted? || record.invalid? save!
- kbenson 11y agoThe behavior here, if it comes from Ruby, almost definitely has it's legacy in Perl, so you can look to Perl for justifications. The main justification is likely to be that's a natural construct of how we think and communicate, so why not allow us to express ourselves that way? Another way to look at it is why do you think the conditional should come before like you've shown? Because C or even older languages started with that? If you didn't have prior experience with that form, would you still think it's inherently better, or would the trade-offs between the two forms seem slightly more balanced?
- matthewmacleod 11y agoI guess it's generally just that it's regarded as fairly idiomatic Ruby. bbatsov's popular style guide, for example (https://github.com/bbatsov/ruby-style-guide#if-as-a-modifier https://github.com/bbatsov/ruby-style-guide#if-as-a-modifier): The same applies to while/until loops, which can lead to quite succinct code. I've been using it for a long time, so I don't find it confusing at all – but I agree it's pretty rare to find, so I'm not surprised to find out some people would rather not see that!