Ruby:定义实例变量的更短方式
Ruby: shorter way to define instance variables
我正在寻找在 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
认识 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
但这会导致多出一个未使用的 class 对象。为什么在不需要时制造垃圾?
我正在寻找在 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
认识 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
但这会导致多出一个未使用的 class 对象。为什么在不需要时制造垃圾?