From: James Edward Gray II Date: 2007-01-19T05:54:32+09:00 Subject: Re: auto assign arguments? On Jan 18, 2007, at 2:13 PM, David Chelimsky wrote: > I see where to put bugs and patches, but this is a feature request. Is > this the right place to submit these? > > In any case, here's a feature request: > > I find that I do a lot of this: > > def initialize(thing, other) > @thing = thing > @other = other > end > > One thing I'd love to see in a future version of ruby is this; > > def initialize(@thing, @other) > end > > ... and have that automagically initialize @thing and @other with the > submitted values. Some thinking-out-loud: #!/usr/bin/env ruby -w class Module def constructor(*attrs) define_method(:initialize) do |*passed| raise ArgumentError, "Wrong number of arguments" \ unless attrs.size == passed.size attrs.each_with_index do |att, i| instance_variable_set("@#{att}", passed[i]) end after_initialize if respond_to? :after_initialize end end end class ABC constructor :a, :b, :c def after_initialize p instance_variables.map { |var| [var, instance_variable_get (var)] }.sort end end ABC.new(1, :two, "three") ABC.new(*%w[testing my code]) # >> [["@a", 1], ["@b", :two], ["@c", "three"]] # >> [["@a", "testing"], ["@b", "my"], ["@c", "code"]] __END__ James Edward Gray II