From: David Gamba Date: 2013-01-06T17:43:46+09:00 Subject: Re: Best practice for &&, ||, and, or On Sat 05 Jan 2013 09:56:38 PM MST, Jan E. wrote: > Dave Aronson wrote in post #1091178: >> No! No! 1000.times :no! ;-) >> >> Consider the difference between "x = true && false" and "x = true and >> false". Since && has HIGHER precedence than =, "x = true && false" is >> equivalent to "x = (true && false)", just as you might expect. > > Why would I expect that? Why would I even *use* assignments in "if" > statements? > > Sorry, but if you use assignments in "if" statements (much too obscure) > without explicit parenthesis (even worse), then I'd say *this* is your > problem, not the implicit operator precedence you somehow consider to be > "wrong". > > Maybe my programming style is totally out of fashion, but my "if" > statements usually look like this: > > if and ( or ) > ... > end > > With being a pure expression (no change of state). In > that context, I want a very low precedence to make sure that each expression> is evaluated *before* and/or takes action. > > And I believe this is the sane way of writing "if" statements. > > When I want to do "magic" like > > var = val || alt > > then I do use &&/||. But this is a very different context. > I totally agree with Jan E. What reason is there for Ruby to have "and" and "or" if you aren't supposed to use them? The problem for most people is that they fail to realize that they are not aliases for && and || respectively. Since they are not aliases they provide different functionality and someone interested in programming with Ruby should research when and how to use them. Again, Jan E. Came up with a good example. One thing that I don't like with ruby precedence however, is that ruby developers decided to give "and" and "or" the same precedence. In my opinion, "or" should have lower precedence than "and", just like in perl, wich allows you to do things like: if and or and Knowing that expression 3 and 4 will only be executed if 1 and 2 are not true. I suppose that they went for left to right readability so you have to evaluate everything as you read it. so to get something similar in ruby you have to write: if ( and e_2>) or ( and ) --DavidG PS: why is there not (or at least an easy to find) an operator precedence table in ruby-doc.com? The ones I found where in different, not official looking websites. 1. http://phrogz.net/ProgrammingRuby/language.html#table_18.4 2. http://www.tutorialspoint.com/ruby/ruby_operators.htm