作者:yzxnha_975 | 来源:互联网 | 2023-05-16 04:04
PossibleDuplicate:Idiomaticobjectcreationinruby可能重复:在ruby中创建惯用对象Therearemanyoccai
Possible Duplicate:
Idiomatic object creation in ruby
可能重复:在ruby中创建惯用对象
There are many occaisions when I have an initialize
method that looks like this:
当我有一个如下所示的initialize方法时,有很多次:
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
)?
其中符号表示实例变量的名称(具有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') # => #
p Foo.new('a', 'b', 'c', 'd') # => #
p Foo.new('a', 'b') # => #
3 个解决方案