0

I have a method with a lot of named arguments, some with default values:

def myClass
  def initialize(a:, b:, c:, d:, e:, f:, g: nil, h: nil, i: nil)
    ...
  end
end

The list is a little hard to look at and comprehend. I am looking for way to make this simpler.

Using a hash for args,

myClass.new(**args)

works, but I can't have both symbols with and without a value.

Is there a way to make this simpler?

sawa
  • 165,429
  • 45
  • 277
  • 381
Nick Ginanto
  • 31,090
  • 47
  • 134
  • 244
  • Named parameters improve quality. Why remove them? if it is hard to look at, just use newlines in the parameter list. Also have a look if some of the parameters belong together and should be collected in a struct or an object. – Meier Mar 15 '16 at 09:55

2 Answers2

0

You could try this

def myClass
  def initialize(args) 
    [:a, :b, :c, :d, :e, :f].each do |a|
      raise ArgumentError.new unless args.has_key?(a)
    end
    ...
  end
end

args is a hash object.

Rohit Jangid
  • 1,077
  • 1
  • 8
  • 19
0

May be there are cases where a function needs such a large number of parameters, but normally this indicates that a function is doing too many things in one place.

Ok, if you want to do it, I would move it into a special private method:

class MyClass
  def initialize(*args) 
    args = set_defaults(args)
  end

  private

  def set_defaults(args)
    # step 1: extract the options hash and check the keys, 
    # if a key doesn't exist so put it in with the default value
    options = args.extract_options! 
    [g: :state, h: 'a name', i: 5].each do |key, value|
      options[key] = value unless options.key?(key)
    end
    # step 2: check the other array elements
    [:a, :b, :c, :d, :e, :f].each do |element|
      raise ArgumentError.new unless args.include?(element)
    end
    # step 3: put them all together again
    args << options
  end
end

BTW: def className doesn't work. It's class ClassName. In addition please have a look at the beautiful ruby style guide - naming.

guitarman
  • 3,290
  • 1
  • 17
  • 27
  • `options[key]` will always return `nil` if the `key` does not exist so explicitly setting it to `nil` is unnecessary. – engineersmnky Mar 15 '16 at 13:03
  • That's right. The intension is to show a way to set default parameters. I will edit the code and set some differnt parameters. – guitarman Mar 15 '16 at 14:29