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 isnil:getsat 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 thedef.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 giveInfinityinstead).syntax errorpointing at the end of the file — usually a missingend.cannot load such file -- geometry (LoadError)— userequire_relativefor 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
rescue, naming the exception class.