Confusion regarding boolean operators

Apologies if this has been asked before (I tried to search).

David and Matz write in their excellent book (Thanks, Gary W., for
the reference) in section 4.6.8 that:

Ruby’s Boolean operators (which I assume mean &&, ||, !, not, and, or)
are not based on methods: classes for example, can not define their own
&& method.

I have two questions in this regard:

  1. Is is applicable to only &&, || etc. and I can still define the !
    method so that !var calls my method? (I find that to be the case, See
    [1])

  2. How is !var converted to a method call var.! ? (which is what I find)

This is with 1.9.2.

Thank you.

-Kedar

[1]
#!/usr/bin/env ruby

class Human
attr_accessor :name
def initialize(name)
@name = name
end
def to_s
“Human: #{@name}, I am not God”
end
end

class God
def !
puts “method ! called”
Human.new(“me”)
end

end
god1 = God.new
puts !god1 # prints Human:me, I am not God

Hi,

it looks like the ! unary operator is now definable in ruby-1.9.2.
This is something that has changed from the 1.8.X series, which may
explain why the documentation error.

Not all operators can be overridden, but most of them are. There is a
finite list of them, so it’s not possible to define new-ones (this
would require to change the parser). If they are, they are represented
as a special method to an object. If not, then you can do nothing
about it. The other logic operators are in the latter set.

To understand how it works, basically, when ruby sees one of those
operators, it is like it would rewrite the expression behind the scene
to look like a method call. In that case, “!obj” would become
“obj.!()”. “a + b”, would become “a.+(b)”. The latter expression is
not necessarily a valid syntax because these characters are special,
but you get the idea.

Finally, you can also write :

class God
def [email protected]
end
end

The other unary operator that I know of (-), requires this @ character
to distinguish from a.-(b), which is yet another operator. I find this
to be more readable.

Hope this helps

“Jonas P. (zimbatm)” [email protected] writes:

it looks like the ! unary operator is now definable in ruby-1.9.2.
This is something that has changed from the 1.8.X series, which may
explain why the documentation error.

I am nit-picking here, but it’s possible since 1.9 in general (or at
least 1.9.1, I couldn’t test it with 1.9.0), not just 1.9.2.

Finally, you can also write :

class God
def [email protected]
end
end

The other unary operator that I know of (-), requires this @ character
to distinguish from a.-(b), which is yet another operator. I find this
to be more readable.

Hope this helps

Thanks, zimbatm.

-Kedar