如何运行Ruby生成的字节码?

brvekthn  于 12个月前  发布在  Ruby
关注(0)|答案(2)|浏览(98)

我是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

我不知道如何通过使用生成的字节码来执行相同的脚本。
有谁能告诉我如何执行这个。
提前感谢!

nkkqxpd9

nkkqxpd91#

**TL;DR;**您正在查找.eval方法。

.compile方法将返回RubyVM::InstructionSequence类的一个示例,该类具有.eval方法,用于评估/运行您的“编译”指令。

iseq = RubyVM::InstructionSequence.compile("x = 50; x > 100 ? 'foo' : 'bar'")    
iseq.eval       # => "bar"

或者,一个oneliner:

RubyVM::InstructionSequence.compile("x = 50; x > 100 ? 'foo' : 'bar'").eval
58wvjzkj

58wvjzkj2#

RBC

#!/usr/bin/env ruby

byte_code = RubyVM::InstructionSequence.compile_file ARGV[0]
File.open(ARGV[1], 'w') do |f|
  f.write <<~RUBY
            #!/usr/bin/env ruby

            RubyVM::InstructionSequence.load_from_binary(DATA.read).eval

            __END__
          RUBY
end
File.open(ARGV[1], 'ab') { |f| f.write byte_code.to_binary }

# or FileUtils.chmod('+x', ARGV[1]), if you don't mind requiring 'fileutils'
File.chmod(0775, ARGV[1])

hello.rb

puts 'Hello world'

运行

$ ./rbc hello.rb hello && ./hello
Hello world

请注意,对于多个文件,

相关问题