Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check ruby syntax error in ruby code

Tags:

ruby

I use following now to check syntax error:

system "ruby -wc path/to/file.rb"

but it very waste time if there are too many file(for instance, i refactory code), so my question is: is there way to ruby syntax check in ruby code?

like image 681
cimi3386284gt Avatar asked Dec 03 '14 13:12

cimi3386284gt


People also ask

How do I check the syntax of a Ruby file?

How to check Ruby code syntax: First, Drag and drop your Ruby file or copy / paste your Ruby text directly into the editor above. Finally, you must click on "Check Ruby syntax" button to display if there is an syntax error in your code.

What is syntax error in Ruby?

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 '}'

What syntax does Ruby use?

The syntax of the Ruby programming language is broadly similar to that of Perl and Python. Class and method definitions are signaled by keywords, whereas code blocks can be defined by either keywords or braces. In contrast to Perl, variables are not obligatorily prefixed with a sigil.


2 Answers

Under MRI, you can use RubyVM::InstructionSequence#compile (relevant documentation) to compile Ruby code (which will throw exceptions if there are errors):

2.1.0 :001 > RubyVM::InstructionSequence.compile "a = 1 + 2"
 => <RubyVM::InstructionSequence:<compiled>@<compiled>>

2.1.0 :002 > RubyVM::InstructionSequence.compile "a = 1 + "
<compiled>:1: syntax error, unexpected end-of-input
a = 1 +
        ^
SyntaxError: compile error
        from (irb):2:in `compile'
        from (irb):2
        from /usr/local/rvm/rubies/ruby-2.1.0/bin/irb:11:in `<main>'
like image 75
Chris Heald Avatar answered Oct 01 '22 22:10

Chris Heald


The simplest way is with the command line -c flag:

ruby -c file_you_want_to_check.rb
like image 25
Jonah Avatar answered Oct 02 '22 00:10

Jonah