Rb_require() for strings

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

"Guilherme T." <zarawesome@gmail.com> schrieb im Newsbeitrag
news:57e813c9.0412170459.47d42421@posting.google.com...

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

Guilherme T. wrote:

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