I am concerned about writing self-modifying code in Ruby. And by self-modifying, I mean being able to write functions that take a code block as an input value, and output another code block based on this. (I am not asking about basics such as redefining methods at runtime.)
What I might want to do is, for example, having the following block,
_x_ = lambda { |a, b, c, d| b + c }
one can notice that arguments a
and d
are not used in the body at all, so I would like a function eg. #strip
to remove them,
x = _x_.strip
which should produce same result as writing:
x = lambda { |b, c| b + c }
Now in Lisp, this would be easy, since Lisp code is easily manipulable data. But I do not know how to manipulate Ruby code. I can parse it eg. by
RubyVM::InstructionSequence.disassemble( x )
But how, based on this, do I write a modified block? Other examples of what I would want to do are are eg.
y = lambda { A + B }
y.deconstantize
# should give block same as saying
lambda { |_A, _B| _A + _B }
So far, in Ruby, I have never encountered a situation where I had to concede that something is not possible. But this time, gut feeling tells me that I might have encountered the fundamental weakness of beautifully structured code vs. code with little syntax to speak about (which would be Lisp). Please enlighten me.