K
Kedar Mhaswade
Apologies if this has been asked before (I tried to search).
David and Matz write in their excellent book (Thanks, Gary Wright, 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
David and Matz write in their excellent book (Thanks, Gary Wright, 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