代码之家  ›  专栏  ›  技术社区  ›  DreamWalker

Ruby:定义实例变量的更短方法

  •  3
  • DreamWalker  · 技术社区  · 9 年前

    我正在寻找在 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
    

    Ruby是否有任何内置功能可以避免这种杂耍?

    # 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
    
    1 回复  |  直到 9 年前
        1
  •  10
  •   Sergio Tulentsev    9 年前

    满足 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
    

    我经常看到人们这样使用Struct:

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

    但这会导致一个额外的未使用的类对象。为什么在你不需要的时候制造垃圾?