Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A possible example of separate VM contexts in Ruby. This would be an alternative to using multiple processes.
# The main world out here represents the default Context.
# Each Context is its own environment.
$name = 'Main Context'
context_a =
context_a.eval do
puts $name # nil. Globals are not shared.
$name = 'Context A'
puts $name # Context A
puts $name # Main Context
# Classes are also not shared.
# You can be sure your classes are safe from unwanted modification.
class MyClass
def print_me
puts $name
end # Main Context
context_a.eval do # Raises exception. MyClass doesn't exist.
class MyClass
def print_me
puts $name
end # Context A
# You can send arbitrary data between Contexts.
# In this case, we'll send a hash that tells
# the Context to do something.
context_a.on_receive do |message|
case message[:type]
when :print_my_class
when :new_name
$name = message[:value]
when :main_context_print
message[:value].eval { }
eval_message = { :type => :print_my_class }
new_name_message = { :type => :new_name,
:value => 'Context A (from Main)' }
context_a.send(eval_message) # Context A
context_a.send(eval_message) # Context A (from Main)
context_main = VMContext.current
main_context_message = { :type => :main_context_print,
:value => context_main }
context_a.send(main_context_message) # Main Context
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment