In mail "[ruby-talk:12035] Re: RCR: shortcut for instance variable initialization"
    Dave Thomas <Dave / PragmaticProgrammer.com> wrote:

>        @param1, @param2, @anotherparam = param1, param2, anotherparam

> has a couple of inherent problems.
> 
> First, it's noisy. It clutters up the source, and cuts down on
> communication of _real_ semantic content.
> 
> Second, it's error prone. There are two effective duplications of
> 'param1' in the above, and as you may know, I don't like duplication :)

This is not sufficient?

  class Module
    def auto_iv_init( nm, *params )
      name = nm.id2name
      alias_method "_real_#{name}", nm
      remove_method nm
      module_eval %~
	def #{name}( *args, &block )
	  #{params.collect {|n| '@' + n.id2name }.join(',')} = args
	  _real_#{name}( &block )
	end
      ~
    end
  end

  class C
    def foo
      p @param1
      p @param2
      p @anotherparam
    end
    auto_iv_init :foo,  :param1, :param2, :anotherparam
  end

  C.new.foo( * %w< a b c > )

At least this code does not create duplications (except method name).
Weak points are:

  1. auto_iv_init() call must be placed AFTER definition.
     FYI we can resolve this problem by using method_added()
     and class variable.
  2. better name is required.


Minero Aoki