Syntax errors are one of the most basic errors in Ruby and are encountered when the Ruby compiler cannot parse your code. Here is an example:
# hello-world.rb
x = {id: 1
ruby hello-world.rb
hello-world.rb:1: syntax error, unexpected end-of-input, expecting '}'
In this block of code, we forgot to close the hash literal using a closing curly bracket }
and the ruby parser isn't able to make sense of our code. And, since a SyntaxError
is thrown by the ruby parser before it is executed, it cannot be rescued. This usually points to something unrecoverable. You may also run into this when you compile a piece of code at runtime or include new ruby files:
eval "x = {id: 1"
This block of code tries to compile our previous example using the eval
function while our ruby code is being executed. Since ruby is an interpreted language the distinction between runtime and compile time is blurry. When your ruby code is executed it is first parsed and compiled by the ruby compiler and then executed. And SyntaxError
s are usually raised when ruby is trying to parse your code.
You can catch a syntax error if it is being raised while eval
ing a string or while require
ing a ruby source file.
Capture a syntax error while eval
ing:
begin
eval 'x = {id: 1'
rescue SyntaxError => err
puts "ERROR: #{err.inspect}"
end
Capture a syntax error while require
ing a ruby source file:
begin
require 'syntax_error_demo'
rescue SyntaxError => err
puts "ERROR: #{err.inspect}"
end
» Tips
- Uncaught syntax errors may be shipped to production in the absence of a basic automated test suite. Your test suite should at the very least require all files in your application. This ensures that you won't run into this error in the production environment.
- Rails 5 has disabled autoloading which is one of the causes of delayed feedback of a syntax error. However, if you have a Rails application which depends on an earlier version of Rails, make sure that you add all your paths to the
eager_load_paths
. - Using a good text editor with a proper ruby syntax checking plugin will help you catch these errors quicker.
- You may also run into a syntax error due to incompatible ruby versions. For instance if you are following a document which was written for ruby >= 1.9 you may see a hash literal defined as
u = {id: 3, name: "Danny"}
, which is valid ruby code for versions >= 1.9. However, this isn't valid ruby for versions < 1.9, and you'll get a SyntaxError when you run it.