【问题标题】:Ruby: shorter way to define instance variablesRuby:定义实例变量的更短方法
【发布时间】:2016-06-17 23:54:33
【问题描述】:

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

【问题讨论】:

    标签: ruby ruby-2.1


    【解决方案1】:

    认识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
    

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

    【讨论】:

    • 用这种方式定义类有什么好处?
    • 我的意思是您在回答中使用的方式。
    • 我的回答有两种方式。
    • 回答的第一种方式。
    • @Stefan:这是一种常见的误用,所以我想我会警告不要这样做:)
    猜你喜欢
    • 2011-02-01
    • 2018-02-09
    • 2011-08-27
    • 2014-03-06
    • 2013-05-28
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 2021-06-13
    相关资源
    最近更新 更多