[Ruby]幾個技巧

來源:互聯網
上載者:User
不顯示瀏覽器$HIDE_IE = true 怎樣獲得當前檔案的路徑 File.dirname(__FILE__).to_s

 

 

讀檔案:
第一種方法:
$result='d://rs.txt'
File.open($result, "r") do |file|  
file.each_line do |line|
     if line.length>20
     puts line.chop.length    #去掉最後一個換行字元,並顯示該行實際字串的長度
      puts line
    end
  end
  end
第二種方法:
filename='d://rs.txt'
while File.exists?(filename) #如果源檔案存在就執行下面的操作
file=File.open(filename,'r')
  while (lines=file.gets)
puts lines
end

寫檔案:
$filename="C://Automation//rss"+".txt"
$logfile = File.new($filename,"a")
iCount=0

while(iCount<10)      //迴圈寫入10行
$logfile.puts "http://xxxx/rs#{iCount}.xml"
iCount=iCount+1
end

今天又笨了一次,由於要比較兩個檔案的不同,於是考慮用ruby來寫個指令碼

實現,剛開始的時候使用雙重
File.open($file1, "r") do |file1|  
file1.each_line do |line1|
總是報錯,

後來改成先把檔案讀到一個數組裡,然後迴圈比較,成功.

其實這是個笨方法,在unix下使用三個命令就可以完成了.

1.先使用sort指令將檔案中的資料按照要求的索引進行排序,
2.然後使用uniq指令將重複資料去掉
3.再使用diff命令就可以了.

 

 

並發運行測試

可以啟動多個線程,利用線程來調用方法。

# demonstrate ability to run multiple tests concurrently

require 'thread'

require 'watir' 

def test_google

 ie = Watir::IE.start('http://www.google.com')

 ie.text_field(:name, "q").set("pickaxe")   

 ie.button(:value, "Google Search").click  

 ie.close

end

# run the same test three times concurrently in separate browsers

threads = []

3.times do

 threads << Thread.new {test_google}

end

threads.each {|x| x.join}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.