使用Ruby将变量与变量连接起来

时间:2013-04-08 21:15:10

标签: ruby watir

我正在编写一个测试脚本,打开一个包含URL列表但没有“www”和“com”的文件。

我正在尝试读取每一行并将该行放入URL中。然后我检查它是否重定向甚至存在。

我的问题是当我从文件中读取行并将其分配给变量时。然后我会在加载后与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 /

如何摆脱回报?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

那是因为你的线路被换行线终止了。你需要strip关闭它:

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

请注意,有更好的方法可以迭代文件中的行:

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

答案 2 :(得分:0)

这是将其重新命名为“Ruby方式”后的代码:

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

这是不正确的,因为它错过了end的结束while。但是,它也没有正确处理文件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

相关问题