

Ruby: Is &! documented anywhere? - chrislaco

A while back, due to a typo, I realized you could use &#38;! in ruby statements:<p><pre><code>  if this? &#38;! that?
</code></pre>
was the same as<p><pre><code>  if this? &#38;&#38; !that?
</code></pre>
I've scoured all of the ruby operator docs I can find with no mention of it anywhere.<p>Interestingly, this works:<p><pre><code>  if this? &#38; ! that?
</code></pre>
but this does not:<p><pre><code>  if this? &#38; &#38; that?

</code></pre>
If I ack the ruby source, I don't see &#38;!, but I do see a ton of &#38;&#38;!<p>Wat? Now I'm curious. Anyone know the innards of ruby enough to enlighten me?
======
threedaymonk
It doesn't really work quite as you suggest; it's just that

    
    
        a &! b == a & !b
    

where !b is true if b is nil or false, and false otherwise.

& works as a bitwise AND for numbers, and a logical AND for boolean values.
You can't mix the two, but as long as a is a boolean, you'll get some kind of
result out of the calculation:

    
    
        true &! true  # => false
        true &! false # => true
        true &! 0     # => false
        0    &! 0     # => TypeError: can't convert false into Integer

------
Slackwise
Only when working with explicit Booleans, yes. Otherwise no:

    
    
        [21] pry(main)> foo = 1
        => 1
        [22] pry(main)> bar = false
        => false
        [23] pry(main)> foo && !bar
        => true
        [24] pry(main)> foo &! bar
        TypeError: can't convert true into Integer
        from (pry):24:in `&'
    

In this case, the behavior is inappropriate in that Ruby evaluates only false
and nil for False, and everything else as True.

I'm going to assume this is some quirk or "feature" as part of the bitwise
operator '&'.

