Demonstrate how to dynamically add variables to an object (a class instance) at runtime.

This is useful when the methods/variables of an instance are based on a data file that isn't available until runtime. Hal Fulton gives an example of creating an OO CSV parser at An Exercise in Metaprogramming with Ruby. This is referred to as "monkeypatching" by Pythonistas and some others.

 
link ximage
 
procedure main()
   c1 := foo(1,2)                            # instance of foo
   write("c1:\n",ximage(c1))
   c1 := extend(c1,["c","d"],[8,9])          # 2 new fields
   write("new c1:\n",ximage(c1))
   c1 := extend(c1,["e"],[7])                # 1 more
   write("newest c1:\n",ximage(c1))   
end
 
class foo(a,b)                               # dummy class
end
 
procedure extend(instance,newvars,newvals)   #: extend a class instance 
   every put(f := [],fieldnames(instance))   # copy existing fieldnames
   c := ["tempconstructor"] ||| f            # new constructor    
   every put(c,!newvars)                     # append new vars
   t := constructor!c                        # new constructor
   x := t()                                  # new instance
   every x[v := !f] := instance[v]           # same as old instance  
   x.__s := x                                # new self 
   if \newvals then 
      every i := 1 to min(*newvars,*newvals) do 
         x[newvars[i]] := newvals[i]         # add new vars = values   
   return x
end