Let the code string be code. The standard way is to do something like this:
begin
RubyVM::InstructionSequence.compile(code)
nil
rescue Exception => e
... # Put code here to return `e` itself, print its message, or whatever you like
end
If an error is raised and is rescued, that error will display the syntax error. If not (and nil is returned), then code is syntactically valid Ruby code (which does not guarantee that it is free of other types of errors).
The comments saying it is dangerous to do, etc, does not seem to make sense.
ruby -c?