ArgumentError

An opinionated beast. You'll know when you're wrong.

Ruby's ArgumentError class

Raised when the arguments are wrong and there isn't a more specific Exception class.

Ex: passing the wrong number of arguments

[1, 2, 3].first(4, 5)

raises the exception:

ArgumentError: wrong number of arguments (given 2, expected 1)

Ex: passing an argument that is not acceptable:

[1, 2, 3].first(-4)

raises the exception:

ArgumentError: negative array size

Superclass

StandardError

Enemies

Honeybadger

Children

» Making a Strong Argument

Ruby's ArgumentError is raised when you call a method with incorrect arguments. There are several ways in which an argument could be considered incorrect in Ruby:

  • The number of arguments (arity) is wrong
  • The value of the argument is unacceptable
  • The keyword is unknown when using keyword arguments

Because Ruby itself uses ArgumentError in these conditions, many Ruby developers extend the pattern when building their own methods.

For example, say that you have a list of creatures and want to print the most popular:

CREATURES = ['NoMethodError', 'TypeError', 'ArgumentError', 'RuntimeError']

def top(n)
  puts CREATURES[0...n]
end

top(2) # =>
# NoMethodError
# TypeError

Since there are 4 creatures, calling top with an argument up to 4 will print 4 values. However, what happens when we call top with an argument of 5?

top(5) # =>
# NoMethodError
# TypeError
# ArgumentError
# RuntimeError

Since there are 4 values in the array, 4 are printed. This could be confusing if our calling code is expecting 5 values. Let's make our method raise an exception when the argument is larger than the total number of values in the array:

def top(n)
  raise ArgumentError.new(
    "Expected a value of 1-#{CREATURES.size}, got #{n}"
  ) if CREATURES.size < n

  puts CREATURES[0...n]
end

Now, when we call top(5), we get a helpful error telling us exactly what we did wrong:

top(5) # => ArgumentError: Expected a value of 1-4, got 5

» Extra Credit

What happens if you call the top method with zero, or a negative value? If you're new to ruby, try extending top to raise ArgumentError for these exceptional cases!

» Argument vs. Parameter: Did You Know?

You may have seen the terms argument and parameter used (seemingly) interchangeably when discussing method definitions. That's because there is a slight distinction between these two terms! Let's revisit our top method:

def top(number)
  puts CREATURES[0...number]
end

The word number on the first line of the method definition is called a parameter. It hasn't been used to call the method yet. Now, say you want to call the method you've created:

top(100)

The value 100 that you're passing to the top method is called an argument.