Possible Duplicate:
Idiomatic object creation in ruby
There are many occaisions when I have an initialize
method that looks like this:
class Foo
def initialize bar, buz, ...
@bar, @buz, ... = bar, buz, ...
end
end
Is there a way to do this with a simple command like:
class Foo
attr_constructor :bar, :buz, ...
end
where the symbols represent the name of the instance variables (with the spirit/flavor of attr_accessor
, attr_reader
, attr_writer
)?
I was wondering if there is a built in way or a more elegant way of doing something like this:
class Class
def attr_constructor *vars
define_method("initialize") do |*vals|
vars.zip(vals){|var, val| instance_variable_set("@#{var}", val)}
end
end
end
so that I can use it like this:
class Foo
attr_constructor :foo, :bar, :buz
end
p Foo.new('a', 'b', 'c') # => #<Foo:0x93f3e4c @foo="a", @bar="b", @buz="c">
p Foo.new('a', 'b', 'c', 'd') # => #<Foo:0x93f3e4d @foo="a", @bar="b", @buz="c">
p Foo.new('a', 'b') # => #<Foo:0x93f3e4e @foo="a", @bar="b", @buz=nil>