如何在Ruby中生成初始化程序?

现在是时候缩短它了:

class Foo attr_accessor :a, :b, :c, :d, :e def initialize(a, b, c, d, e) @a = a @b = b @c = c @d = d @e = e end end 

我们有’attr_accessor’来生成getter和setter。

我们有什么要按属性生成初始值设定项吗?

最简单的:

 Foo = Struct.new( :a, :b, :c ) 

生成访问器和初始化器。 您可以进一步自定义您的课程:

 Foo = Struct.new( … ) do def some_method … end end 

我们可以创建像def_initializer这样的东西:

 # Create a new Module-level method "def_initializer" class Module def def_initializer(*args) self.class_eval < 

你可以使用类似构造函数的gem。 从描述:

声明性意味着通过将哈希传递给构造函数来定义对象属性,构造函数将设置相应的ivars。

它很容易使用:

 Class Foo constructor :a, :b, :c, :d, :e, :accessors => true end foo = Foo.new(:a => 'hello world', :b => 'b',:c => 'c', :d => 'd', :e => 'e') puts foo.a # 'hello world' 

如果您不想使用访问器生成的ivars,可以不使用:accessors => true

希望这有助于/ Salernost

 class Foo class InvalidAttrbute < StandardError; end ACCESSORS = [:a, :b, :c, :d, :e] ACCESSORS.each{ |atr| attr_accessor atr } def initialize(args) args.each do |atr, val| raise InvalidAttrbute, "Invalid attribute for Foo class: #{atr}" unless ACCESSORS.include? atr instance_variable_set("@#{atr}", val) end end end foo = Foo.new(a: 1) puts foo.a #=> 1 foo = Foo.new(invalid: 1) #=> Exception 
 class Module def initialize_with( *names ) define_method :initialize do |*args| names.zip(args).each do |name,val| instance_variable_set :"@#{name}", val end end end end