2

I am writing a test script that opens a file with a list of URLs without the "www" and "com".

I am trying to read each line and put the line into the URL. I then check to see if it redirects or even exists.

My problem is when I read the line from the file and assign it to a variable. I then do a compare with what's in the URL after loading and what I initially put in there, but it seems to be adding a return after my variable.

Basically it is always saying redirect because it puts "http://www.line\n.com/".

How can I get rid of the "\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

Basically it is always saying redirect because it puts http://www.line and then return .com/

How can I get rid of the return?

4

3 に答える 3

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
于 2013-04-08T21:24:53.683 に答える
3

これは、行が改行で終了しているためです。あなたはstripそれをオフにする必要があります:

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

ファイル内の行を反復処理するより良い方法があることに注意してください。

File.foreach("Data/activeSites.txt") do |line|
  # ...
end
于 2013-04-08T21:18:29.220 に答える