[Ruby]几个技巧

来源:互联网 发布:单片机外部脉冲计数器 编辑:程序博客网 时间:2024/04/29 09:28
不显示浏览器
$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}

原创粉丝点击