Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h1>Using hash</h1> <p>Since ruby-1.9, <a href="http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash/" rel="nofollow">hash keys order is guaranteed</a>. A simple solution here would be to take advantage of that, by putting your requests in a hash and storing their result accessing the hash element by its key :</p> <pre><code>requests = { foo: [ 'a', 1 ], bar: [ 'b', 5 ], foobar: [ 'c', 2 ] } requests.each do |name, config| Thread.new( name, config ) do |name, config| sleep config[1] requests[ name ] = config[0] end end sleep 6 requests.each do |name, result| puts "#{name} : #{result}" end </code></pre> <p>Produces :</p> <pre><code>foo : a bar : b foobar : c </code></pre> <p>Thus, to match your provided code :</p> <pre><code>stop, i, text, requests = false, 0, '', {} until stop i += 1 requests[ i ] = nil Thread.new( i ) do |key| r = RestClient.post 'http://example.com' requests[ i ] = r.to_str sleep 1 # after a treatment, the value of stop will set to true end end # you will have to join threads, here text = requests.values.join </code></pre> <h1>Using array</h1> <p>If the last example is good for you, you could even simplify that using an array. Array order is of course guaranteed too, and you can take advantage of ruby array dynamic size nature :</p> <pre><code>a = [] a[5] = 1 p a =&gt; [nil, nil, nil, nil, nil, 1] </code></pre> <p>So, previous example can be rewritten :</p> <pre><code>stop, i, text, requests = false, 0, '', [] until stop i += 1 Thread.new( i ) do |key| r = RestClient.post 'http://example.com' requests[ i ] = r.to_str sleep 1 # after a treatment, the value of stop will set to true end end # you will have to join threads, here text = requests.join </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload