I'm looking for the shorter way to define instance variables inside the initialize method:
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
Does Ruby have any in-build feature which lets to avoid this kind of monkey job?
# 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
Meet Struct, a tool made just for this!
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
I often see people use Struct like this:
class MyStruct < Struct.new(:foo, :bar, :baz, :qux)
end
But this results in one additional unused class object. Why create garbage when you don't need to?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With