8 ms·
Ruby Demystified: and vs. &&
- klochner 14y agotldr: && has higher operator precedence than "and" Significantly, "&&" > "=" > "and", which can lead to unintended results when refactoring "&&" --> "and"
- trebor 14y agoI.E.: why you should always use && instead of "and".
- meepmorp 14y agoSo why have both?
- Skoofoo 14y agoYou guys would benefit from reading the article.
- Smudge 14y agoRead the article.
- meepmorp 14y agoI did. And I still don't see why you'd have both. It seems like a landmine for someone learning the language and a place for bugs to creep in to code. Pick one and go with it. The extra expressiveness or whatever a ruby person would call it, that comes from the alternate forms just doesn't seem worth it.
- Smudge 14y ago> Pick one and go with it. They did. It's `&&` and `||`. I understand your point when it comes to it being a potential landmine, and honestly I never use them myself. But I've never seen any ruby guides or docs use `and` instead of `&&`, and I have seen skilled rubyists make great (and correct) use of `and`.
- meepmorp 14y ago> They did. It's `&&` and `||`. I assume you mean idiomatically chosen, since clearly the decision wasn't made at the language level. > I have seen skilled rubyists make great (and correct) use of `and`. I'm obviously not a ruby programmer, so it doesn't matter much to me, but it seems odd to argue that having a largely disused second set of logical operators in a language that skilled people periodically trot out for some cases is anything but a design wart. Maybe it's a cultural thing in the ruby world. And, honestly, I don't mean that to sound snide or slighting. It's just odd to me.
- Smudge 14y agoFair point. It is a bit odd. IIUC the low/reverse-precedence operators came from Perl, and whether or not to use them is just a stylistic choice. It's clear what this means: > raise "ooops" unless do_something() But even so, it reads a bit backwards. Some codebases do this instead: > do_something() or raise "oops" That's just repeating one of the examples in the article, but it jumps out to me as the one I've seen most often.
- NateDad 14y agoI never understood what Perl (and now Ruby) has against if statements. foo or do_something() is exactly the same as if foo { do_something() } Except the latter is WAY less likely to be accidentally misread.... and don't even get me started on do_something() unless foo
- Smudge 14y agoIt's all just a matter of taste and preference. If you find yourself consistently misreading commonplace ruby, maybe ruby isn't for you.
- nsmartt 14y agoTo avoid a potentially useful language feature because you might make a mistake with it is, to me, a absurd. A much better argument might be Use <feature> only when you fully grasp its use, which is true of any feature. Some are more difficult to understand than others, especially when trying to relate a feature to another language, but that's just not an argument I can support.
- RegEx 14y agoIt might not just be you working. Sure, use things that you understand. The problem comes when you aren't even aware you don't understand due to subtleties you may have not encountered yet. Then you do some debugging, do some googling, and bam, now it's "obvious to anyone with half a brain, everyone should just RTFM"
- nsmartt 14y agoI understand the potential harm when working with teams, but I also recognize that it's a shame to limit your use of the language to avoid potential trouble. Surely there's some middle ground to be found over dogma such as Never use <feature>. I'm not suggesting that everyone should understand every detail of every potentially misunderstood feature. I'm suggesting that these situations should be dealt with on a case-by-case basis.
- eCa 14y agoNo. You should use them appropriately.
- danielweber 14y agoSeeing "and" or "or" in Ruby code now leaps out at me with danger signs. I've decided it's just not worth it.
- aston 14y agoNot to start a language war, but this blog post demonstrates two things Python got right that Ruby got wrong. First, in Python, there's only one way to express a boolean "and". The && operator is left out. Second, this post demonstrates a danger of allowing assignment via '=' evaluate to an expression (granted with less weird precedence rules it wouldn't turn out as bad in this case).
- tinco 14y agoNot to acknowledge we are at war, but allow me to react to your act of war. This article demonstrates one thing that Ruby does awesomely, and python does not at all. Wether that makes Ruby better than Python.. well yes it does, no point in being diplomatic now, we're at war! In Ruby there is only one way to express a boolean and, it goes: &&. Besides the boolean and there is also a binary operator with the name `and` which evaluates its left child, _and_ when it is true returns the value of its right child. In this way it mimics the way we build sentences, that's smart. That's intuitive. That's Ruby.
- baddox 14y agoMy biggest complaint is that you called Ruby's way "intuitive."
- deleted 14y ago[deleted]
- aardvark179 14y agoBoth && and and are short-circuiting operators in Ruby. To eagerly evaluate both operator arguments you would need to use &.
- InAnEmergency 14y ago"&" isn't even the same category, since it is a definable method and its meaning varies with the value on the left hand side.
- jabagonuts 14y ago
- danso 14y ago> When I first started learning Ruby, I was excited to discover that Ruby has the keywords and and or as boolean operators. I quickly got into the habit of writing all of my boolean statements with these, instead of the more conventional && and ||, because my code became so much readable pry(main)> a = true && false pry(main)> a = true and false Hmm...I dunno, I don't think the latter is necessarily easier to read than the former. The use of the symbols helps, for me at least, to delineate between value/variables and operators. Those symbols aren't pretty but their ugliness can serve a purpose. I don't mind using them in SQL, but only because SQL is case-insensitive and I can stick to the style of making all syntax uppercase.
- tinco 14y agoThis article isn't about replacing symbols with words, ruby isn't about replacing symbols with words either, and there is no place in the article where the author states that a = true and false is prettier than a = true && false And if you would actually have read the article and paid close attention you would have learned that the two lines you just said are not functionally equivalent. No ruby programmer would ever have a line that says a = true and false It just makes no sense. Maybe a very experienced ninja ruby programmer would, but that programmer would know exactly what he was doing. The beauty in ruby and in the 'and' keyword is that a ruby programmer intuitively knows when to use which. This article just clears up why exactly they work like you expect them to work. edit: maybe a weird programmer would do something like this @message = "We failed :(" and false at the end of a function that has conditionals with return statements in them.
- danso 14y agoWow, I must have missed the point. Because I could've sworn the OP was talking about how he thought that 'and' and 'or' could be stand-in's for && and ||, but he found out that they aren't quite equivalent. Because if they were equivalent, he would substitute words for symbols because, as I quoted, "[his] code became so much readable." I'm not evaluating what he discovered at the end of the post. I'm evaluating his original intent for using 'and' and 'or' in the first place, which was readability. I'm simply stating my opinion on that comparison. And yes, "a = true and false" doesn't make sense. I just copy-pasted his sample code as a quick example. I didn't expect people to take it literally, as if I were showing off a best practice.
- pyre 14y agoThis is basically the author finding out something in Ruby that was copied from Perl. E.g. it allows one to do: $fh = open() or die("File did not open") Instead of: $fh = open() die("File did not open") unless $fh
- thedufer 14y agoWhat's wrong with $fh = open() || die("File did not open") ? The only difference is that the results of `die` are assigned to `$fh`, but I don't think `die` even returns. It still short-circuits.
- pyre 14y agoMaybe not in this specific instance, but both operators have different behaviour and different uses.
- draegtun 14y agoNothing is wrong with that. However the actual Perl open() would be like this... open my $fh, '<', 'file.txt' or die "file.txt not found"; open(my $fh, '<', 'file.txt') || die 'file.txt not found'; Above two lines are equivalent.
- eaurouge 14y agoMakes for an interesting blog post, I guess. But precedence for "&&" and "||" in Ruby are similar to precedence for "&&" and "||" in C, Java and others, and they are similar to precedence rules for "and" and "or" in Python. Precedence rules for "and" and "or" in Ruby are an anomaly not just in the Ruby world but in many (most?) mainstream languages.
- smsm42 14y ago"In many (most?) mainstream languages" doesn't really agree with "anomaly". If it's in most mainstream languages, then it's not an anomaly, it's the norm.
- pacaro 14y agoIt seems to me that Ruby's "and" and "or" are more similar to Prolog's ','/2 and ';'/2 ([Edit] not that Prolog is necessary a shining example of a mainstream programming language)
- amalag 14y agoIt was an interesting experiment while it lasted, but I don't think they make sense.
- graywh 14y agoand and or are control-flow modifiers like if and unless. http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/ http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/
- smsm42 14y agoOperator precedence (and && vs. and with different precedence) has been around since forever - this particular one since Perl was a fresh and novel thing at least. If it's a mystery that needs "demystifying" for somebody, it's time to hit the books.
- deleted 14y ago[deleted]
- deleted 14y ago[deleted]
- static_typed 14y agoIf this will help the brogrammers and fauxgrammers in the ruby world to take security and software engineering seriously, then it is a good thing.
- InAnEmergency 14y agoI think I may be the last person who still thinks "and/or" are just fine for boolean expressions in Ruby. It is true that "and/or" are not equivalent to "&&/||". But I don't find any of the arguments that we should then avoid "and/or" in favor of "&&/||" convincing.
- sabat 14y agoYup. They're like any other tool. If you're not sure how to use and/or, then don't use them. Or, better yet, study up. Programming can benefit from nuance.
- Falling3 14y agoNot that I want Ruby to be anything like PHP and Perl, but this is the same thing that happens in those languages due to the difference in precedence of and, &&.
- kyllo 14y agoIt's no accident. Ruby is heavily influenced by Perl.
- Falling3 14y agoOh I know... someone said ruby is two parts Perl, one part Python, and one part Smalltalk. I like to think it's a bit less Perl than that, but my judgement is clouded - I'm a bit of a Perl hater.
- kyllo 14y agoI think it's a little less Perl than that, and a little more Lisp than that. I don't have enough Perl experience to have a strong opinion on it, but I know that Matz says he created Ruby because he wanted a language that was more powerful than Perl and more object-oriented than Python. Ruby is a little bipolar in that sense. It's both highly functional and highly object-oriented, for an imperative language. Even more of a "Swiss-army chainsaw" than Perl.
- eLobato 14y agotl;dr: '&&' is a boolean and 'and' is for control flow
- NateDad 14y agoI don't know why everyone thinks a race to the fewest lines of code is a good thing.