3

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

1 Answer 1

10

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?

Sign up to request clarification or add additional context in comments.

9 Comments

What is the advantage of defining class with this way?
I mean the way that you are using in your answer.
There are two ways in my answer.
First way in your answer.
@Stefan: it's a common mis-usage, so I thought I'd warn not to do it :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.