The low-precedence or works in just the same way, short-circuiting execution of its right-hand side if its left-hand side evaluates to a truth-y value anything but false or nil. It is most commonly used to throw errors if something goes wrong. I prefer the or version in this case as the code gets run from left to right, the same way it is read. Watch out, though, as the and and or keywords still have slightly higher precedence than their more mainstream control-flow cohorts if , unless , while , and until.
This means that operations chained together with with and and or always get evaluated from left to right. When the first argument of the AND function i. Well, in this case the value is not false , so the value of the first expression is returned instead.
The ones in the inner parenthesis. And because of the short-circuit evaluation , the first value is returned. Thus the value of the expression is true. The right hand side is never evaluated if the left hand side is truthy. So the previous example could be written like this. Hash vs. Another good explanation here: devblog. That's a great way of putting it, really made it "click" in my head. And or is like a reversed unless modifier. Combine this answer with the details of tadman's answer and you get the whole picture.
Avdi updated his take on when to use and vs. Basically use 'and' and 'or' for control flow because of their lower precedence. Show 2 more comments. Since the assignment returns a logically true value :foo then the second part evaluates, which fails, returning nil. Andrew Grimm Andrew Grimm AndrewGrimm, thanks, good to know.
Sorry for trolling but I'm sincerely confused with some aspects of ruby reality. One thing is sure - every ruby project needs strict style policies to keep the codebase maintainable. Gabe Kopley Gabe Kopley But for an unassuming user, problems might occur if it is used along with other operators whose precedence are in between, for example, the assignment operator: def happy? Santhosh Santhosh BKSpurgeon See here for a ordered list of operator precedence in Ruby.
Feuda Feuda 2, 25 25 silver badges 24 24 bronze badges. Kevin Ng Kevin Ng 2, 1 1 gold badge 11 11 silver badges 17 17 bronze badges. JakubArnold Sarcasm is never helpful. Examples sometimes are.
BobRodes It wasn't a sarcasm. There are 7 answers, 6 of which already have examples.
0コメント