正如标题所提到的,我需要让用户输入一些Ruby脚本代码,我的脚本将存储它们以供以后调用.如何在不实际评估的情况下检查用户输入语法?
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)
归档时间: |
|
查看次数: |
294 次 |
最近记录: |