On 7/8/07, Ari Brown <ari / aribrown.com> wrote:
> I was talking about actual code modifications. Could Ruby modify it's
> own code? Take this example...
>
> Ruby asks the user the URL of a code modification thing (eg, a
> cleaner version of a patch, or just a patch).
>
>         What is the URL?
>                 http://www.awesomesauce.net/awesome.rb
>         Downloading....
> And then Ruby would make modifications to its own code.

I'm not sure Ruby, the interpreter, can, but a Ruby /script/ can.

Since you can reopen classes, it's possible to load arbitrary source
code, evaluate it (or just use 'load'), and then have the changes
reflected.

For example, if your main file was something like this (untested!):

require 'open-uri'
class X; def foo; "bar"; end; end
puts X.new.foo    # => "bar"
puts "What is the URL?"
eval open(gets).read
puts X.new.foo    # => "no bar for you"

And some remote Ruby file called "something.rb" was like this:

class X; def foo; "no bar for you"; end; end

And you ran the first file and specified
http://domain.com/something.rb .. then, in theory, (and this is all
untested), the functionality of the initial program is changed. You
could then, in theory, save the "patch" to a local file and add it to
a list of "patches" to apply on future executions. Rails' use of
plugins treads into some of these areas.

This all gets dangerous very quickly though, but I just wanted to
answer the question you asked as I hadn't seen any answers so far (you
mean polymorphic, as in polymorphic viruses, rather than polymorphism,
it seems).

Cheers,
Peter Cooper
http://www.rubyinside.com/