Post by Peter Cooper on August 4th, 2006

Dynamically adding methods to classes through their objects

Lucas Carlson comes up with a cute trick to make Ruby feel a little more like a prototyped language by allowing you to define methods on a class in real-time through child objects, like so:

f = Foo.new
f.greet = lambda {|t| "Hello #{t}!"}
f.greet "Lucas Carlson" # => Hello Lucas Carlson!

j = Foo.new
j.greet "World" # => Hello World!

Find out how. A cute trick.

2 Responses to “Dynamically adding methods to classes through their objects”

  1. #1
    Kent Says:

    require 'ostruct'

  2. #2
    Joey Says:

    Kent, if it works how I think it works(I havent checked yet), OpenStruct won't work.

    f = OpenStruct.new
    f.puts = lamba{|t|puts t}
    f.puts(1) #=> gives you a proc