在有些时候,我们不想把我们的代码外传,这时候最好的做法就是编译我们的代码
1.创建一个简单的ruby程序
$ nano -w fibonacci.rb
PHI = (1+Math.sqrt(5))/2
def fibonacci(n)
((PHI ** n) - ((-PHI) ** -n)) / Math.sqrt(5)
end
puts fibonacci(100)
2.创建一个编译转换器
$ nano -w compiler.rb
# compiler.rb
source_code = File.open(ARGV[0], 'r') # load the file from arguments
compiled_code = RubyVM::InstructionSequence.compile(source_code)
binary_code = compiled_code.to_binary
binary_file = File.open(ARGV[0].split('.').first + '.bin', 'w+')
binary_file.puts binary_code
binary_file.close
我们来加密
$ ruby compiler.rb fibonacci.rb
3.创建一个二进制码执行器
$ nano -w exec.rb
# exec.rb
executable_binary_code = File.open(ARGV[0], 'r').readlines.join('')
compiled_instruction_sequence = RubyVM::InstructionSequence.load_from_binary(executable_binary_code)
compiled_instruction_sequence.eval
4.我们来运行一下
$ ruby exec.rb fibonacci.bin