Tuesday, July 29, 2014

How to return value from loaded file?

Have you ever wanted to get return value from file which is read with Kernel#load without resorting to global variables or constants. It is actually quite simple when you realize that you can use non-local exit (continuations) to do that.

File a.rb:

class Foo
  def bar
    puts "bar"
  end
end

throw :value, "hello"

File main.rb:

value = catch :value do
  load File.expand_path('a.rb')
end
print "a.rb returned value '#{value}'\n"
Foo.new.bar

Output:

a.rb returned value 'hello'
bar

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.