2016-03-04 43 views
3

我正在寻找更短的方式来定义initialize方法内实例变量:红宝石:更短的方式来定义实例变量

class MyClass 
    attr_accessor :foo, :bar, :baz, :qux 
    # Typing same stuff all the time is boring 
    def initialize(foo, bar, baz, qux) 
    @foo, @bar, @baz, @qux = foo, bar, baz, qux 
    end 
end 

红宝石是否有任何建造功能,它可以让以避免这种猴子的工作?

# e. g. 
class MyClass 
    attr_accessor :foo, :bar, :baz, :qux 
    # Typing same stuff all the time is boring 
    def initialize(foo, bar, baz, qux) 
    # Leveraging built-in language feature 
    # instance variables are defined automatically 
    end 
end 

回答

10

遇见Struct,一个专为此而做的工具!

MyClass = Struct.new(:foo, :bar, :baz, :qux) do 
    # Define your other methods here. 
    # Initializer/accessors will be generated for you. 
end 

mc = MyClass.new(1) 
mc.foo # => 1 
mc.bar # => nil 

我经常看到有人使用结构是这样的:

class MyStruct < Struct.new(:foo, :bar, :baz, :qux) 
end 

但是这导致一个额外的未使用的类对象。为什么在不需要时创建垃圾?

+0

用这种方法定义类有什么好处? –

+0

你的意思是哪条路? –

+0

我的意思是你在你的答案中使用的方式。 –