gpt4 book ai didi

ruby - 使用 Ruby 将字符串与变量连接起来

转载 作者:数据小太阳 更新时间:2023-10-29 08:18:39 25 4
gpt4 key购买 nike

我正在编写一个测试脚本,用于打开一个文件,其中包含不带“www”和“com”的 URL 列表。

我正在尝试读取每一行并将该行放入 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/

我怎样才能摆脱返回?

最佳答案

简答: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

关于ruby - 使用 Ruby 将字符串与变量连接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15889134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com