DreamWalker
DreamWalker

Reputation: 1387

Ruby: shorter way to define instance variables

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

Upvotes: 3

Views: 99

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230441

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?

Upvotes: 10

Related Questions