Common errors

What NoMethodError on nil, NameError, ArgumentError, TypeError, ZeroDivisionError and SyntaxError mean and how to fix them.

Runs in Zerethon IDE · Ruby 4.0 Official Ruby documentation ↗

Ruby prints the file and line, the message and the error class in parentheses, then the calls that led there. The first line is usually where to look.

  • undefined method 'chomp' for nil (NoMethodError) — a value you expected is nil: gets at the end of input, a missing hash key, an index past the end of an array.
  • undefined local variable or method 'x' for main (NameError) — a typo, or the variable was defined inside another method or block.
  • wrong number of arguments (given 1, expected 2) (ArgumentError) — the call does not match the def.
  • no implicit conversion of Integer into String (TypeError) — "Age: " + 36; use interpolation "Age: #{age}" or .to_s.
  • divided by 0 (ZeroDivisionError) — integer division by zero (floats give Infinity instead).
  • syntax error pointing at the end of the file — usually a missing end.
  • cannot load such file -- geometry (LoadError) — use require_relative for your own files, and check the name.
main.rb
values = ["10", "x", "7"]
total = 0
values.each do |v|
  total += Integer(v)
rescue ArgumentError
  puts "skipped #{v.inspect}"
end
puts "total: #{total}"

Output

skipped "x"
total: 17
Handle an error you expect with rescue, naming the exception class.