From: Jesús Gabriel y Galán on
On Thu, Aug 12, 2010 at 5:09 AM, Paul Harrington <xeno(a)badenoughdu.de> wrote:
> Pen Ttt wrote:
>> probem1:
>> the following program can only run  in irb console,it can't run with
>> command :
>> ruby /home/test.rb,why?
>> require 'rubygems'
>> require 'net/http'
>> threads = []
>> open("/home/pt/test/data","a+") do |wfile|
>> str=%w(http://table.finance.yahoo.com/table.csv?s=IBM
>> http://table.finance.yahoo.com/table.csv?s=YHOO
>> http://table.finance.yahoo.com/table.csv?s=AACC)
>> for page_to_fetch in str
>>    Thread.new(page_to_fetch) do |url|
>>     info = Net::HTTP.get_response(URI.parse(url)).body
>>     puts info
>>    end
>>  end
>> threads.each {|thr| thr.join}
>> end
>
> threads is still an empty array. Try adding each thread to threads as
> you create it.

An idiom I usually use is this:

threads = str.map do
Thread.new [...snip...]
end

threads.each {|t| t.join}

Jesus.

From: Brian Candler on
Or simply:

threads << Thread.new do
...
end

--
Posted via http://www.ruby-forum.com/.

From: Brian Candler on
Jesús Gabriel y Galán wrote:
> But you still need the outer iteration. If I'm already iterating with
> #each, I change it to map to do both things at the same time :-)

Of course. But for a newcomer to ruby (who is still using 'for' instead
of 'each'), it may be easier to take one step at a time along the road
to enlightenment.

Step 1:

threads = []
for page in str
threads << Thread.new do
...
end
end

Step 2:

threads = []
str.each do |page|
threads << Thread.new do
...
end
end

Step 3:

threads = str.map do |page|
Thread.new do
...
end
end
--
Posted via http://www.ruby-forum.com/.

From: Jesús Gabriel y Galán on
On Thu, Aug 12, 2010 at 9:53 AM, Brian Candler <b.candler(a)pobox.com> wrote:
> Or simply:
>
>  threads << Thread.new do
>    ...
>  end

But you still need the outer iteration. If I'm already iterating with
#each, I change it to map to do both things at the same time :-)

Jesus.

From: Jesús Gabriel y Galán on
On Thu, Aug 12, 2010 at 10:49 AM, Brian Candler <b.candler(a)pobox.com> wrote:
> Jesús Gabriel y Galán wrote:
>> But you still need the outer iteration. If I'm already iterating with
>> #each, I change it to map to do both things at the same time :-)
>
> Of course. But for a newcomer to ruby (who is still using 'for' instead
> of 'each'), it may be easier to take one step at a time along the road
> to enlightenment.

Yes, you are right.


>
> Step 1:
>
> threads = []
> for page in str
>  threads << Thread.new do
>    ...
>  end
> end
>
> Step 2:
>
> threads = []
> str.each do |page|
>  threads << Thread.new do
>    ...
>  end
> end
>
> Step 3:
>
> threads = str.map do |page|
>  Thread.new do
>    ...
>  end
> end