Want to stay on top? Ruby Weekly is a once-weekly e-mail newsletter covering the latest Ruby and Rails news.
     Feed Icon

Dynamically adding methods to classes through their objects

By Peter Cooper / August 4, 2006

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.

Comments

  1. Kent says:

    require 'ostruct'

  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

Other Posts to Enjoy

Twitter Mentions