rb_require() for strings

G

Guilherme T.

I'd like to use rb_require(), but instead of a filename give it a
string with the contents to be required. How would I go about doing
this?

Thanks in advance
 
R

Robert Klemme

Guilherme T. said:
I'd like to use rb_require(), but instead of a filename give it a
string with the contents to be required. How would I go about doing
this?

What you want to do is basically execute a piece of code once, right? In
that case you could do something like this:

Cheap solution:

$code_snippets ||= Hash.new {|h,code| h
Code:
 = eval( code ) }


# will print "buh!" only once
$code_snippets[ 'puts "buh"' ]
# ...
$code_snippets[ 'puts "buh"' ]


A bit nicer

module Code
def self.snippets
@code_snippets ||= Hash.new {|h,code| h[code] = eval( code ) }
end

def self.require( code )
snippets[ code ]
end
end

# will print "bah!" only once
Code.require 'puts "bah!"'
Code.require 'puts "bah!"'
Code.require 'puts "bah!"'
Code.require 'puts "bah!"'

Regards

robert
 
C

Charles Mills

Guilherme said:
I'd like to use rb_require(), but instead of a filename give it a
string with the contents to be required. How would I go about doing
this?

Thanks in advance

I think you want rb_eval_string() from ruby.h
Basically the string you pass is evaluated by the parser. For example:
rb_eval_string("puts 'hey'");
would return Qnil and print "hey\n" to standard out.

Others you may want to consider:
$ grep rb_eval *.h
intern.h:VALUE rb_eval_cmd _((VALUE, VALUE, int));
ruby.h:VALUE rb_eval_string _((const char*));
ruby.h:VALUE rb_eval_string_protect _((const char*, int*));
ruby.h:VALUE rb_eval_string_wrap _((const char*, int*));

-Charlie
 

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

Members online

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top