rubyinstance-variables

How to avoid instance variable initializing ugliness


I see this popping up all the time in my code

class Foo
  def initialize(foo)
    @foo = foo
  end
  #...
end

This isn't too bad, but it gets worse:

class Foo
  def initialize(foo,baz,bar,a,b,c,d)
    @foo = foo
    @baz = baz
    @bar = bar
    #etc...

You can sortof get around this by doing something like

@foo, @baz, @bar = foo, baz, bar

But even that feels wrong and is annoying to type. Is there a better way to define instance variables according to arguments?

Edit: There seem to be 2 distinct solutions to this problem. See:


Solution

  • You might want to consider using a Struct:

    class Foo < Struct.new(foo,baz,bar,a,b,c,d)
    end
    
    foo = Foo.new(1,2,3,4,5,6,7)
    foo.bar #=> 2
    

    No need to define an extra initialize method at all...