Ruby Demystified: and vs. &&(blog.tinfoilsecurity.com) |
Ruby Demystified: and vs. &&(blog.tinfoilsecurity.com) |
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).
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.
I like the way you put that. I always stumble for a moment when asked to explain why using "and" and "&&" interchangeably is not a good idea because it can lead to subtle bugs in your program. Maybe a mnemonic would help to remember this more easily.
left && right is true or false, but
left and right is right when true
or something along those lines.The problem is that "just like English" does not always translate to "intuitive for a programming language". Programmers don't have a problem with learning a new set of rules that don't work the same as their native language, because programming isn't (and shouldn't be) like writing a letter to your computer.
The simple rule is "if it's a binary operator, it has higher precedence than assignment". That rule works for almost every binary operator in almost every language. Show me an exception (like the comma operator in C), and I'll show you an operator that confuses the hell out of most programmers.
| In this way it mimics the way we build sentences,
| that's smart. That's intuitive. That's Ruby.
That's also a nod to Perl. :PI think it's just an issue of precedence. Assignment evaluates to an expression in all Lisps, ML, Haskell, Scala, and Rust, without this issue.
Stricter typing can also solve the problem. If assignment evaluates to unit, as it does in ML/Haskell/Scala/Rust to name a few, then the attempt to perform the logical-and operation with unit and bool would throw (in a dynamically typed language) or won't compile (in a statically typed language).
One (ruby/perl: &&, python: and) is used to evaluate truthness of two expressions.
The other (ruby/perl: and, python: N/A) is more of a program flow operator. Now that I think about it.. If it is a Tim Toady, it is more of _if_ vs _and_ rather than _&&_ vs _and_.
$fh = open() or die("File did not open")
Instead of: $fh = open()
die("File did not open") unless $fh $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. 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. and and or are control-flow modifiers like if and unless.
http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/Significantly, "&&" > "=" > "and", which can lead to unintended results when refactoring "&&" --> "and"
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.
([Edit] not that Prolog is necessary a shining example of a mainstream programming language)
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.
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.
'&&' is a boolean and 'and' is for control flow
(user isActive) and (user.expiry before now)
and I think that really is more readable than '&&', in a way that your example obscures because you're still using '>' and 'false'.I personally like the Haskell/OCaml approach of having operators just be normal functions that happen to be parsed in infix position. It's simple, elegant, uniform and flexible.
Either way, the core idea is that operators should be nothing special.
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.> 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.
And I definitely agree with danso and disagree with the blog on this issue: the operators gives more structure to the code and makes it much easier to parse at a glance. With the 'and' version, I have to actually read the code to figure out what its doing; with the '&&' version, I can get the basic idea just from the code's "shape" (for lack of a better word).
I think being able to quickly grasp the idea at a glance is far more important than having code look like English.
Something like this, you mean?
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
If you would actually have read the article (or even just the comment you replied to) and paid close attention you would have learned that it said precisely that.
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.
1.9.3p392 :001 > true && 1
=> 1
1.9.3p392 :002 > true and 1
=> 1
1.9.3p392 :003 > false && 1
=> false
1.9.3p392 :004 > false and 1
=> false
1.9.3p392 :005 > nil && 1
=> nil
1.9.3p392 :006 > nil and 1
=> nil
Which is why explicitly checking for "true" or "false" in a conditional is unusual.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.
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.
Since that is the case, I fully agree with you and shouldn't have been so snarky. I apologize :(
(and predicate-1? predicate-2?) if (true && false == true) {
return new BooleanFactory(true);
} else {
return new BooleanFactory(false);
}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.
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`.
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.
> 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.
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