DEV Community

Discussion on: Basic Concurrency in Ruby. Really Basic.

chrisfrank profile image
chrisfrank • Edited


Thanks for taking the time to bring clear documentation into the ruby community. For writing complex concurrent code, concurrent-ruby is an excellent library--but for simple concurrency like API calls, it may be overkill. Ruby actually has solid concurrency built into its standard library, via its Thread class.

To make multiple API calls simultaneously with threads, following your example above, you'd do something like this:

call_1 = { some_api_all }
call_2 = { some_other_api_all }

response_1 = call_1.value
response_2 = call_2.value

Here's the same idea, with less repetition:

data = ["https://some_api",  "https://another_api"].map { |url| { SomeHttpLibrary.get(url) }
}.map { |thread| thread.value }
# data is an array of API responses [response1, response2]

Check this blog post from Thoughtbot for more on how threads work. I have no affiliation with Thoughtbot, I just think their blog is a great resource for rubyists of all experience levels.

briankephart profile image
Brian Kephart

Thanks for the reply, and for adding another (better!) approach.

I used concurrent-ruby because it was already in my project as a Rails 5 dependency, so when I started my search it seemed like the obvious tool for the job. Now it turns out what I needed was in the standard library all along, go figure.