只检查要被证明的字符串的语法,而不是在Ruby中评估

xis*_*xis 4 ruby string eval

正如标题所提到的,我需要让用户输入一些Ruby脚本代码,我的脚本将存储它们以供以后调用.如何在不实际评估的情况下检查用户输入语法?

saw*_*awa 7

def correct_syntax? code
  stderr = $stderr
  $stderr.reopen(IO::NULL)
  RubyVM::InstructionSequence.compile(code)
  true
rescue Exception
  false
ensure
  $stderr.reopen(stderr)
end

correct_syntax?("def foo; end") # => true
correct_syntax?("foo") # => true
correct_syntax?("def foo; en")  # => false
correct_syntax?("foo bar") # => false
Run Code Online (Sandbox Code Playgroud)

  • 今天我学到了[`RubyVM`](http://ruby-doc.org/core-1.9.3/RubyVM.html) (2认同)