"Avi Bryant" <avi.bryant / gmail.com> wrote in message

> (How many times does instance_variable_set get
> used with a value that is *never* referenced directly as @ivar?)

I use it often to generate method definitions dynamically using closures
(without strings and eval).

class Class
  def has_many coll, type=Object
    coll = coll.to_s
    iv = ('@'  + coll).intern

    getter = coll
    setter = (coll + '=').intern
    appender = ('append_to_' + coll).intern

    define_method getter do
      instance_variable_get iv
    end

    define_method setter do |c|
      assert c.all? { |x| type === x }
      instance_variable_set iv, c
    end

    define_method appender do |x|
      assert type === x
      (instance_variable_get iv) << x
    end

  end
end

class House
  has_many :windows
end

This usage will increase in Ruby 1.9+ and 2.0 since closures can take &block
parameters, and closure param lists look just like method param lists.