我是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 我不知道如何使用生成的字节码来执行相同的脚本。
任何人请解释我如何执行这件事。
提前感谢!
发布于 2016-07-05 06:35:43
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'").evalhttps://stackoverflow.com/questions/38195290
复制相似问题