Ruby method with maximum number of parameters

我是研究僧i 提交于 2019-12-03 05:33:42

问题


I have a method, that should accept maximum 2 arguments. Its code is like this:

def method (*args)
  if args.length < 3 then
    puts args.collect
  else
    puts "Enter correct number of  arguments"
  end
end

Is there more elegant way to specify it?


回答1:


You have several alternatives, depending on how much you want the method to be verbose and strict.

# force max 2 args
def foo(*args)
  raise ArgumentError, "Too many arguments" if args.length > 2
end

# silently ignore other args
def foo(*args)
  one, two = *args
  # use local vars one and two
end

# let the interpreter do its job
def foo(one, two)
end

# let the interpreter do its job
# with defaults
def foo(one, two = "default")
end



回答2:


if the maximum is two arguments, why use the splat operator like that at all? Just be explicit. (unless there is some other constraint that you haven't told us about.)

def foo(arg1, arg2)
  # ...
end

Or...

def foo(arg1, arg2=some_default)
  # ...
end

Or even...

def foo(arg1=some_default, arg2=some_other_default)
  # ...
end



回答3:


Raise an error better. If the arguments are not correct, this is serious problem, which shouldn't pass in your with a humble puts.

def method (*args)
  raise ArgumentError.new("Enter correct number of  arguments") unless args.length < 3
  puts args.collect
end


来源:https://stackoverflow.com/questions/4967735/ruby-method-with-maximum-number-of-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!