Ruby学习过程中积累下来的测试代码(进阶)

本文介绍了Ruby编程中的Fiber和多线程应用,展示了如何利用Fiber进行文件读取和计数统计,以及通过多线程实现网页抓取。此外,还讨论了如何避免竞态条件并给出了调用Windows API和编写Ruby扩展的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Fiber:

counts = Hash.new(0) 
File.foreach("D:/rails.txt") do |line| 
   line.scan(/\w+/) do |word| 
     word = word.downcase 
     counts[word] += 1 
   end 
end 
counts.keys.sort.each{ |k| puts "#{k}:#{counts[k]}"} 

###########################################################

words = Fiber.new do 
  File.foreach("D:/rails.txt") do |line| 
    line.scan(/\w+/) do |word| 
        Fiber.yield word.downcase 
     end 
  end 
end
counts = Hash.new(0) 
while word = words.resume 
  counts[word] += 1 
end 
counts.keys.sort.each{ |k| puts "#{k}:#{counts[k]}"} 
另外的例子:

twos = Fiber.new do
  num = 2
  loop do
    Fiber.yield(num) unless num % 3 == 0
    num += 2
  end
end
10.times { print twos.resume, " " } 
多线程:

require 'net/http'
pages = %w( www.sina.com.cn www.yahoo.com www.sohu.com )
threads = []
for page_to_fetch in pages
  threads << Thread.new(page_to_fetch) do |url|
    h = Net::HTTP.new(url, 80)
    print "Fetching: #{url}\n"
    resp = h.get('/')
    print "Got #{url}: #{resp.message}\n"
  end
end
threads.each { |thr| thr.join }

Race Condition (来自Ruby编程的代码,但是在测试时没有发现Ruby1.9.3)

def inc(n)
  n+1
end
sum = 0
threads = (1..10).map do
  Thread.new do
    10_000.times do
      sum = inc(sum)
    end
  end
end
threads.each(&:join)
p sum
据说应该使用Mutex来锁住对象以防止race condition

def inc(n)
  n+1
end
sum = 0
mutex = Mutex.new
threads = (1..10).map do
  Thread.new do
    10_000.times do
      mutex.lock
      sum = inc(sum)
      mutex.unlock
    end
  end
end
threads.each(&:join)
p sum

Ruby调用Window API

require 'win32ole' 
$urls = [] 
def navigate(url) 
  $urls << url 
end 

def stop_msg_loop
  puts "IE has exited..."
  throw :done
end

def default_handler(event, *args)
  case event
     when "BeforeNavigate"
        puts "Now Navigating to #{args[0]}..."
     end
  end

  ie = WIN32OLE.new('InternetExplorer.Application')
  ie.visible = TRUE
  #ie.gohome
  ie.navigate("http://www.baidu.com")
  ev = WIN32OLE_EVENT.new(ie, 'DWebBrowserEvents')

  ev.on_event {|*args| default_handler(*args)}
  ev.on_event("NavigateComplete") {|url| navigate(url)}
  ev.on_event("Quit") {|*args| stop_msg_loop}

  catch(:done) do
    loop do
      WIN32OLE_EVENT.message_loop
    end
  end

  puts  "You  Navigated to the following URLs:  " 
  $urls.each_with_index do |url, i| 
  puts  "(#{i+1}) #{url}" 
end

自己写Ruby扩展:

http://www.rubyinside.com/how-to-create-a-ruby-extension-in-c-in-under-5-minutes-100.html

ruby-doc.org/docs/ProgrammingRuby/html/ext_ruby.html

http://extensions.rubyforge.org/rdoc/index.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值