In ruby, I often find myself writing the following:
class Foo
def initialize(bar, baz)
@bar = bar
@baz = baz
end
<< more stuff >>
I asked a duplicate question, and suggested my own answer there, expecting for a better one, but a satisfactory one did not appear. I will post my own one.
Define a class method like the following along the spirit of attr_accessor, attr_reader, attr_writer methods.
class Class
def attr_constructor *vars
define_method("initialize") do |*vals|
vars.zip(vals){|var, val| instance_variable_set("@#{var}", val)}
end
end
end
Then, you can use it like this:
class Foo
attr_constructor :foo, :bar, :buz
end
p Foo.new('a', 'b', 'c') # => #
p Foo.new('a', 'b', 'c', 'd') # => #
p Foo.new('a', 'b') # => #