2013-04-08 86 views
2

我正在編寫一個測試腳本,它打開一個包含沒有「www」和「com」的URL列表的文件。使用Ruby與變量串聯字符串

我想讀取每一行並將該行放入URL中。然後我檢查它是否重定向或甚至存在。

我的問題是當我從文件中讀取行並將其分配給一個變量。然後,我在加載之後和最初放入的內容中對網址中的內容進行了比較,但似乎在我的變量之後添加了一個返回值。

基本上它總是說重定向,因爲它把「http://www.line \ n.com/」。

我該如何擺脫「\ n」?

counter = 1 
    file = File.new("Data/activeSites.txt", "r") 
     while (line = file.gets) 
       puts "#{counter}: #{line}" 
       counter = counter + 1 
       browser.goto("http://www." + line + ".com/") 

if browser.url == "http://www." + line + ".com/" 
        puts "Did not redirect" 
       else 
        puts ("Redirected to " + browser.url) 
        #puts ("http://www." + line + ".com/") 
        puts "http://www.#{line}.com/" 
       end 

基本上它總是說重定向,因爲它使http://www.line,然後返回的.com/

我怎樣才能擺脫回報?

+4

你的縮進很糟糕,它使你的代碼非常不愉快的閱讀。請使用一致的縮進。 – meagar 2013-04-08 21:18:57

回答

6

簡短的回答:strip

"text\n ".strip # => "text" 

長一點的回答:

你的代碼不是非常類似ruby的,可以重構。

# Using File#each_line, the line will not include the newline character 
# Adding with_index will add the current line index as a parameter to the block 
File.open("Data/activeSites.txt").each_line.with_index do |line, counter| 
    puts "#{counter + 1}: #{line}" 

    # You're using this 3 times already, let's make it a variable 
    url = "http://#{line}.com" 

    browser.goto(url) 

    if browser.url == url 
    puts "Did not redirect" 
    else 
    puts ("Redirected to " + browser.url) 
    puts url 
    end 
end 
3

這是因爲你的行被換行符終止。你需要strip它關閉:

while (line = file.gets) 
    line.strip! 
    puts "#{counter}: #{line}" 
    # ... 

需要注意的是,有超過一個文件中的行迭代的更好的方法:

File.foreach("Data/activeSites.txt") do |line| 
    # ... 
end 
0

這是它重新縮進到「紅寶石路」後,你的代碼:

counter = 1 
file = File.new("Data/activeSites.txt", "r") 
while (line = file.gets) 
    puts "#{counter}: #{line}" 
    counter = counter + 1 
    browser.goto("http://www." + line + ".com/") 

    if browser.url == "http://www." + line + ".com/" 
    puts "Did not redirect" 
    else 
    puts ("Redirected to " + browser.url) 
    #puts ("http://www." + line + ".com/") 
    puts "http://www.#{line}.com/" 
    end 

因爲它缺少了while關閉end這是不正確的。但是,它也不能正確處理文件IO。

這是我怎麼會寫:

File.foreach("Data/activeSites.txt") do |line| 
    puts "#{ $. }: #{ line }" 

    browser.goto("http://www.#{ line }.com/") 

    if browser.url == "http://www.#{ line }.com/" 
    puts "Did not redirect" 
    else 
    puts "Redirected to #{ browser.url }" 
    puts "http://www.#{ line }.com/" 
    end 
end 

File.foreach是從IO繼承的方法。如果您正確讀取文件,則不需要stripchomp,因爲當IO.foreach讀取該行時,Ruby將正確處理該文件。

每次IO讀取一行時,它會增加全局的$.,這對於$INPUT_LINE_NUMBER來說是短暫的。沒有必要保留一個櫃檯。使用:

require 'english' 

將啓用詳細名稱。有關更多信息,請參見the English docs