我是 Ruby 脚本语言的新手。
我正在学习如何在 Ruby 中生成字节码。 我找到了生成字节码的答案。
但我不知道如何运行生成的字节码。我在网上搜索过,但我没有得到这个问题的答案。
生成字节码:-
puts RubyVM::InstructionSequence.compile("x = 50; x > 100 ? 'foo' : 'bar'").disassemble
输出是,
== disasm: <RubyVM::InstructionSequence:<compiled>@<compiled>>==========
local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1] s1)
[ 2] x
0000 trace 1 ( 1)
0002 putobject 50
0004 setlocal x
0006 trace 1
0008 getlocal x
0010 putobject 100
0012 opt_gt <ic:1>
0014 branchunless 20
0016 putstring "foo"
0018 leave
0019 pop
0020 putstring "bar"
0022 leave
我不知道如何使用生成的字节码来执行相同的脚本。
任何人请向我解释如何执行此操作。
提前致谢!
最佳答案
TL;DR; 您正在寻找 .eval
方法。
.compile
方法会返回一个 RubyVM::InstructionSequence
类的实例,它有 .eval
方法来评估/运行你的“编译”指令。
iseq = RubyVM::InstructionSequence.compile("x = 50; x > 100 ? 'foo' : 'bar'")
iseq.eval # => "bar"
或者,单线:
RubyVM::InstructionSequence.compile("x = 50; x > 100 ? 'foo' : 'bar'").eval
关于ruby-on-rails - 如何运行ruby生成的字节码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38195290/