我正在寻找在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
答案 0 :(得分: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
我经常看到人们像这样使用Struct:
class MyStruct < Struct.new(:foo, :bar, :baz, :qux)
end
但这导致另外一个未使用的类对象。为什么在你不需要的时候制造垃圾?