

Ruby Demystified: and vs. && - angelirizarry
http://blog.tinfoilsecurity.com/ruby-demystified-and-vs

======
aston
Not 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
Not 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.

~~~
jabagonuts
"which evaluates its left child, _and_ when it is true returns the value of
its right child"

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.

~~~
InAnEmergency
That seems more confusing, since they evaluate to the same thing.

    
    
        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.

------
pyre
This 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
What'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.

~~~
draegtun
Nothing 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.

------
graywh

      and and or are control-flow modifiers like if and unless.
    

<http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/>

------
klochner
tldr: && has higher operator precedence than "and"

Significantly, "&&" > "=" > "and", which can lead to unintended results when
refactoring "&&" --> "and"

~~~
trebor
I.E.: why you should _always_ use && instead of "and".

~~~
meepmorp
So why have both?

~~~
Smudge
Read the article.

~~~
meepmorp
I 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
> 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
> 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.

~~~
NateDad
I 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
It's all just a matter of taste and preference. If you find yourself
consistently misreading commonplace ruby, maybe ruby isn't for you.

------
eaurouge
Makes 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
"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.

------
InAnEmergency
I 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
Yup. 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.

------
smsm42
Operator 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.

------
danielweber
Seeing "and" or "or" in Ruby code now leaps out at me with danger signs. I've
decided it's just not worth it.

~~~
caw
I've never actually seen "and" or "or" in Ruby code. I very frequently see it
in Perl code.

~~~
knotty66
I see it fairly often in Rails controllers, e.g.

render :action => "some_action" and return

------
danso
> _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
This 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
Wow, 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.

~~~
tinco
Hmm you're absolutely right. I guess I'm projecting, I just read that as using
`and` and `or` in places that seemed logical to him, but the paragraph is
quite clear in that he just replaced all instances of the symbols with the
words.

Since that is the case, I fully agree with you and shouldn't have been so
snarky. I apologize :(

~~~
danso
Well, it's a Friday afternoon :) You were right I didn't read to the very end
(I kind of guessed what the OP was going to conclude)...I was mostly
interested in seeing of other people thought 'and' and 'or' were good Ruby
idioms to use (ignoring the precedence confusion).

------
eLobato
tl;dr:

'&&' is a boolean and 'and' is for control flow

------
Falling3
Not 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
It's no accident. Ruby is heavily influenced by Perl.

~~~
Falling3
Oh 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
I 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.

------
NateDad
I don't know why everyone thinks a race to the fewest lines of code is a good
thing.

------
amalag
It was an interesting experiment while it lasted, but I don't think they make
sense.

------
static_typed
If this will help the brogrammers and fauxgrammers in the ruby world to take
security and software engineering seriously, then it is a good thing.

