当我尝试通过用户输入获取 URL 时,Ruby open-uri 抛出 Bad uri 错误。为什么?

Ruby open-uri throws an Bad uri error when I try to get a URL through user input. Why?

当我直接在脚本中提供 URL 时,这段代码工作正常。

require 'nokogiri'
require 'open-uri'

get_url = "http://google.com"

doc = Nokogiri::HTML(open(get_url))
puts doc

我尝试在用户输入中输入“http://google.com”,但这不起作用并抛出 Bad uri 错误并显示

No such file or directory @ rb_sysopen

require 'nokogiri'
require 'open-uri'

get_url = gets

doc = Nokogiri::HTML(open(get_url))
puts doc

谁能告诉我我做错了什么?我也尝试查看 google 但没有直接的答案。

gets 在字符串末尾添加一个换行符。我在下面使用了 chomp 来删除它。

现在应该可以了

require 'nokogiri'
require 'open-uri'

get_url = gets.chomp

doc = Nokogiri::HTML(open(get_url))
puts doc