I have a sexp in a file and i want to read in and then run it in ruby. Whenever I try to run it, it tells me SexpTypeError,
exp must be a Sexp, was String:
Is there a way to run the Sexp
from file?
I am using the ruby2ruby gem
and ruby_parser
gems.
I've tried on Windows 10, ruby 2.6. I've tried parsing it after reading it, but it replicates the s-expression that i have in file which does not work.
ruby = "def a\n puts 'A'\nend\n\ndef b\n a\nend\na"
parser = RubyParser.new
ruby2ruby = Ruby2Ruby.new
sexp = parser.process(ruby)
from_file =nil
File.open('jkl', 'wb')do |file|
file.write(sexp)
end
File.open('jkl', 'rb') do |fp|
from_file = fp.read()
end
eval ruby2ruby.process(from_file)
I would like for the code to run giving the output "A"
You have to transform the string into sexp back. E. g. instance_eval
would do.
require 'ruby_parser'
require 'ruby2ruby'
ruby = "def a\n puts 'A'\nend\n\ndef b\n a\nend\na"
parser = RubyParser.new
ruby2ruby = Ruby2Ruby.new
sexp = parser.process(ruby)
File.open('jkl', 'wb') { |file| file.write(sexp) }
from_file = File.open('jkl', 'rb', &:read)
# ⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓⇓
eval ruby2ruby.process(instance_eval(from_file))
b()
#⇒ A