我正在寻找在方法中定义实例变量的更短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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
Ser*_*sev 10
Meet 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
Run Code Online (Sandbox Code Playgroud)
我经常看到人们像这样使用Struct:
class MyStruct < Struct.new(:foo, :bar, :baz, :qux)
end
Run Code Online (Sandbox Code Playgroud)
但是这导致一个额外的未使用的类对象.为什么在不需要时创建垃圾?
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |