4 ms·
The given example of "unless myvariable.nil?" is a little bit awkard. In fact, the use of the "unless" keyword is, in my opinion, almost always awkward unless i
by texel 16y ago
The given example of "unless myvariable.nil?" is a little bit awkard. In fact, the use of the "unless" keyword is, in my opinion, almost always awkward unless it's postfixed: "do_a_thing unless wait?"
Not only that, but most of the time, the expression could simply be written "if myvariable; ...; end", seeing as the vast majority of the time, we only care if the thing we're testing is falsy.
Ruby does give you the tools to be very expressive, indeed almost conversational in your coding style, but it also gives you enough rope to hang yourself.
- draegtun 16y agoDamian Conway in Perl Best Practices recommends not to use negative control statements at all (unless and until). So this would be a no-no: unless ($this > $that) { do_something(); } He's happy they're used to postfix statements however he says that these should only be used for flow control. For eg. for my $i (@list) { next unless $i % 2 == 0; do_something(); }
- draegtun 16y agoCorrection: Conway says don't use postfix unless, for, while or until So last example should be: for my $i (@list) { next if not $i % 2 == 0; do_something(); } Personally I don't follow the bible to the letter :) I do use prefix & postfix unless but only with simple truth conditions like this: unless ($this) { ... } next unless $this;
- GrandMasterBirt 16y agoExpressiveness is important. I remember many times reading logic and missing the little tinsy ! before a giant expression not making the quick flag in my mind raise indicating that this is a unless, not an if. In ruby the idea of the unless is not to save typing. In fact if !foo is easier to write than unless foo. However after a tad bit of getting used to it, you realize that it becomes immediately obvious when skimming the code what the operation is doing. The idea is lets leave the brainpower for the hard problems, and not require you to use all that brainpower to figure out the plumbing.