1

In my last Question I was looking for a way to extend the abilities of Ruby-variables. Answering this lead me to a new question. Apparently "monkey patching" is what solved a huge chunk of that problem, now I can at least do my typing indirectly with something along the lines of (a = 3).nat where nat is a method "monkeypatched" into Fixnum checking weather "3" is a valid value. This is ok for a start but still a bit clumsy and unintuitive. What I really need in the end is a way to rewrite, extend, intercept or overload to constructor for Fixnum so that a = 3 directly calls the method nat.

Is there a way to do this?

I am not only interested in a "proper way", it can be a bit "hacky". This is only for my research, it can be a dangerous, unsupported way.

Community
  • 1
  • 1
HolgerS
  • 87
  • 7

1 Answers1

2

In your example a constructor is not called, what is happening is that you are making a a reference to the literal 3 through the use of the assignment operator =.

What you want is to overwrite assignment which is not possible AFAIK.

Radu Stoenescu
  • 3,187
  • 9
  • 28
  • 45
  • Ah, I should have thought about how Ruby works first - so yes, overwriting or extending assignment would be an awesome solution. But what about where the class Fixnum gets called during the assignment? Is there no way of intercepting or extending or even redirecting that call? – HolgerS Aug 28 '12 at 15:48
  • There is no call in the snippet you posted. Assignment is not a method call and a literal is not a method call. – Jörg W Mittag Aug 29 '12 at 02:29
  • Yes, I understood that, but There has to be some kind of mechanism or function that makes "a" point at "Fixnum". Something that decides that the literal 3 is a Fixnum and thus is connected to Fixnum. Don't get me wrong here, I am not looking for a proper or well crafted solution, I am just looking for any solution, I would not mind having to build an extension for the Ruby Interpreter at worst, or use some unstable hack at best. – HolgerS Aug 29 '12 at 13:18