I think the logical and bitwise operators should call coerce: I have
needed this functionality myself. But you can solve it like this:
class Fixnum
alias_method :_bwor, ![]()
def |(n)
if (n.kind_of?(Numeric))
_bwor n
else
a = n.coerce(self)
a[0] | a[1]
end
end
end
class TrueClass
def coerce(other)
[other,1]
end
end
class FalseClass
def coerce(other)
[other,0]
end
end
8 | false # => 8
8 | true # => 9
Stephen
Yukihiro Matsumoto wrote:
···
Hi,
In message "when will coerce be called?" > on 04/07/15, "Xiangyu Yang" <xiangyu.yang@gmail.com> writes:
>I want to treat "true" as 1 and "false" as 0. So I do:
>class TrueClass
>def coerce(other)
>[other,1]
>end
>end>But the code works only for +, -; not for &, |.
>Why?"coerce" is only used for numeric operators, not logical operators.
You can redefine "to_int" for the purpose (tough I don't recommend).matz.