HolgerS
HolgerS

Reputation: 87

Ruby - add constructor to Fixnum and other classes

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.

Upvotes: 1

Views: 223

Answers (1)

Radu Stoenescu
Radu Stoenescu

Reputation: 3205

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.

Upvotes: 2

Related Questions