Home > Back-end >  Ruby use array as class arguments
Ruby use array as class arguments

Time:10-09

I am making a class with a ton of arguments. I will have other classes with similar arguments.

I don't want to type all the arguments multiple times. I'm looking to do something like this:

argList = [arg1, arg2, arg3, ... arg100]

class myClass1
  def initialize(*argList)
    # ...
  end
end

class myClass2
  def initialize(*argList, extraArg1, ...)
    # ...
  end
end

But this doesn't work because the elements of argList are undefined variables.

So, is there a way to use an array as class arguments?

CodePudding user response:

The elements of argList will not be undefined at run time. If you comment out that line the following code runs fine.

# argList = [arg1, arg2, arg3, ... arg100]

class MyClass1
  def initialize(*argList)
    p *argList
    arg1, arg2, arg3 = *argList
    puts "arg1 = #{arg1}"
    # ...
  end
end

class MyClass2
  def initialize(*argList, extraArg1)
    p *argList
    puts "extraArg1 = #{extraArg1}"
    # ...
  end
end

my1 = MyClass1.new(1,2,3)
my3 = MyClass2.new(4,5,6,7)

@spickermann's comments still hold. It would be strange for any method to require 100 named arguments. What are the "arguments" you are passing in, is it just an array of things you will process? In that case just pass in an array not a splat-array. Are they parameters representing some complex object? In which case maybe you should consider creating the object, potentially a composed object, and passing that in. Maybe you want to consider passing in a Hash object?

  • Related