From: jbshaldane@... (haldane) Date: 2002-02-14T22:59:04+09:00 Subject: Bitwise operators ability to coerce This discussion continued from RubyGarden on request of matz... >I notice that none of the bitwise operators have the ability to coerce - >so in my class Foo (which has an attribute @value)... > def initialize(n) > @value=n > end > def coerce (number) > [Foo.new(number), self] > end > def | (n) > if n.is_a? Foo > @value | n.value > else > @value | n > end > end >..does not work as intended. It looks to me like this ability could >easily be added in numeric.c - how about it? >haldane. __ >When you want to define "coerce" method to convert your object to integers, >I guess there's better conversion scheme: >to_int. >The object that defines "to_int" behave like integers. >matz. __ >Yes, to_int would be ok for my example, but not for what I am really doing >- my real-life class does other stuff instead of just returning integers. >It seems inconsistent that all the other numeric operations call coerce >except for the bitwise ones. >There is a work around: to redefine the bitwise operators in class Fixnum >and handle it there - but it would be nicer if all the operators worked alike. >haldane. __ >Could you be more concrete? Or perhaps we can discuss on the ruby-talk list. >Coerce does not have operator information, so that it might not solve your >problem either. >Bitwise operators do not call coerce because they are integer operation. >You can't define bitwise-or between integer and float. >matz. __ What I am doing is generating instructions for another language from my Ruby code. The other language has integers, and arithmetic operations including bitwise ones. So, when I see x.val= y + 2, the + operator causes output of instructions to add 2 to y and returns an 'immediate' object, which the val= method sees and knows to output instructions to take whatever was on the stack and assign it to x. I guess it's a cheap way of getting a parser! So it would be nice to be able to write 3 | x as well as x | 3. For the other operators, coerce is an elegant way for me to do this. I appreciate you don't want to coerce to floats because there are no float bitwise ops. I think the least surprising way for this to work is for Ruby to test if there is a | (or whichever bitwise op) method for whatever object it was passed, and to try to coerce if there is one. What do you think? haldane.