Rumel
Rumel

Reputation: 937

Is it possible to redefine 0 in ruby?

I'm not actually going to use this in anything in case it does actually work but is it possible to redefine 0 to act as 1 in Ruby and 1 to act as 0? Where does FixNum actually hold its value?

Upvotes: 1

Views: 177

Answers (2)

quetzalcoatl
quetzalcoatl

Reputation: 33506

No, I don't think so. I'd be very suprised if you managed to. If you start overriding Fixnum's methods/operators, you maaaybe might get near that (i.e. override + so that 1+5 => 5, 0+5 => 6 etc), but you will not get full replacement of literal '0' with value 1. At least marshalling to native would expose the real 0 value of the Fixnum(0).

To be honest, I'm not really sure if you can even override the core operations like + op on a Fixnum. That could break so many things..

As far as I remember from 1.8.3 source, simple integers and doubles are held right inside a 'value' and are copied all around *). There is no singular "0", "1" or "1000" value. There is no extra dereference that would allow you to swap all the values with one shot. I doubt it changed in 1.9 and I doubt anyone got any weird idea about that in 2.0. But I don't actually know. Still, that would be strange. No platform I know interns integers and floatings.. Strings, sometimes array literals, but numbers?

So, sorry, no #define true false jokes :)

--

*) clarification from Jörg W Mittag (thanks, this is exactly what I was referring to):

(..) Fixnums do not have a place in memory, their pointer value is "magic" (in that it cannot possibly occur in a Ruby program) and treated specially by the runtime system. Read up on "tagged pointer representation", e.g. here.

Upvotes: 1

dfherr
dfherr

Reputation: 1642

Assignment does not alias Fixnum objects. There is effectively only one Fixnum object instance for any given integer value, so, for example, you cannot add a singleton method to a Fixnum. Any attempt to add a singleton method to a Fixnum object will raise a TypeError. Source

That pretty much means you can't edit a Fixnum and therefor not redefine 0 or 1 in native ruby.

Though as these Fixnums are also Objects they have unique object id's that cleary reference them somewhere in the memory. See BasicObject#__id__

If you can locate the memory space where 0 and 1 objects are and switch these, you should have effectivle switched 0 and 1 behavior in ruby as now either will reference the other object.

So to answer your question: No redefining Fixnums is not possible in Ruby, switching their behaviour should be possible though.

Upvotes: 0

Related Questions