You could normally use load() to include and execute a Ruby file [source]; but it only works with files, not URLs. If you want to execute Ruby code stored inside a file that you can only access by URL, do it like this:

require 'open-uri'
code_from_url = open('') {|f| }

Note that we include “open-uri” to modify the behavior of open() so as to also be able to open from URLs instead of files [source]. Note also that open() does return the value of the block in this case instead of an IO object, because a block is given [source].

You could also use a different approach where the file is read into an array of lines, but in that case you need to run the eval() calls per line, and supply the same binding (execution environment) to eval() for all these calls, to let later calls refer to variables in prior ones. If not supplying a binding, each eval() will evaluate its line into a new, empty execution environment.

require 'open-uri'
code_as_array = open('') {|f| f.readlines }
env = binding()
code_as_array.each { |line| env.eval(line) }


Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

This site uses Akismet to reduce spam. Learn how your comment data is processed.