32

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?

3 Answers 3

74

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
Sign up to request clarification or add additional context in comments.

Comments

12

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

Comments

5

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

Comments

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.