From: George Ogata Date: 2002-11-24T18:41:19+09:00 Subject: Re: find arguments... is this possible Michael Hale wrote: > I noticed that many times I just hang on to the constuctor variables and > use them later. This code allows me to do that automatically. > > class MyClass > def initialize(first, second) > local_variables.each { |each| eval("@#{each} = #{each}") > } > end > > def a_method > p instance_variables.collect { |each| eval("#{each}") } > end > end > > MyClass.new('val1','val2').a_method > > Produces: > ["val1", "val2"] How about something like: class Class def init_simple(*syms) strs = syms.map {|s| s.id2name} self.module_eval %{def initialize #{strs.join(',')}; #{strs.map {|s| "@#{s} = #{s};"}.join} end} end end Then you just use this to create constructors: class C self.init_simple :a, :b, :c def sum @a + @b + @c end end C.new(1, 2, 3).sum # 6 Alternatively, you can piggyback a Struct: C = Struct.new('C', :a, :b, :c) class C def sum a + b + c end end C.new(1, 2, 3).sum # 6