Method for turning strings into code

J

James Britt

Steve said:
Hi all,

What is the Ruby technique for turning strings into executable code?

There's eval:

eval( 'class Foo;def x; puts "x"; end;end' )

Foo.new.x

And its variants (instance_eval, class_eval)


James
--

http://www.ruby-doc.org - Ruby Help & Documentation
http://www.artima.com/rubycs/ - Ruby Code & Style: Writers wanted
http://www.rubystuff.com - The Ruby Store for Ruby Stuff
http://www.jamesbritt.com - Playing with Better Toys
http://www.30secondrule.com - Building Better Tools
 
S

Steve Litt

Uh, well, that's not the right answer. Eval evaluates
(=executes) a string. It doesn't turn a string into executable
code (=compile).

When I first posed the question, what I really meant was turn it into Ruby
code (like eval does). Sorry for the confusion.

While we're on the subject, do you know of a way to turn a Ruby program into
an executable binary?

Thanks

SteveT

Steve Litt
http://www.troubleshooters.com
(e-mail address removed)
 
S

Steve Litt

Via one of the various forms of eval. However, using eval on arbitrary
strings is insecure, so generally it's considered bad form. There's even
a slogan: "Eval is evil." The preferred technique is to build a solution
using Ruby's dynamic programming facilities.

Where do I find out more about Ruby's dynamic programming facilities?

SteveT

Steve Litt
http://www.troubleshooters.com
(e-mail address removed)
 
J

James Britt

Christian said:
Wrap it in a lambda, then.

If I have a string in a file, would we say it was executable code? Or
does loading it into the Ruby interpreter make it executable code?


What are the differences among

require 'my-file-of-strings'


load 'my-file-of-strings'

and

eval( IO.read( 'my-file-of-strings' ) )



James
--

http://www.ruby-doc.org - Ruby Help & Documentation
http://www.artima.com/rubycs/ - Ruby Code & Style: Writers wanted
http://www.rubystuff.com - The Ruby Store for Ruby Stuff
http://www.jamesbritt.com - Playing with Better Toys
http://www.30secondrule.com - Building Better Tools
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,651
Latest member
VeraPiw932

Latest Threads

Top