4

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

4

1 回答 1

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
于 2013-09-11T19:06:09.050 回答