Create a gist now

Instantly share code, notes, and snippets.

Simple Futures in Ruby with Lambdas and Threads
def future # :block:
thread = Thread.new do
Thread.current.abort_on_exception = false
yield
end
lambda { thread.value }
end
def compose(proc) # :block:
lambda { |*args| yield proc.call(*args) }
end
# Example:
f1 = future {
(1..3).each { puts "Sleeping in #{Thread.current}..."; sleep 1 }
next 1
}
f2 = compose(f1) { |x| x + 1 }
f3 = compose(f2) { |x| x * 2 }
puts "Waiting for result in #{Thread.current}..."
puts f3.call
# Another example (parallel HTTP fetch):
require "open-uri"
urls = ["http://echo.fruktsallad.net/?foo", "http://echo.fruktsallad.net/?bar"]
responses = urls.map { |x| future { open(x).read } }.map(&:call)
results = urls.zip(responses)
# => [["http://echo.fruktsallad.net/?foo", "foo"], ["http://echo.fruktsallad.net/?bar", "bar"]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment