Search code examples
ruby-on-railsrubynokogiriopen-uri

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


This code works fine when I provide URL directly into the script.

require 'nokogiri'
require 'open-uri'

get_url = "http://google.com"

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

I tried entering "http://google.com" in user input but this doesn't work and throws a Bad uri error and says

No such file or directory @ rb_sysopen

require 'nokogiri'
require 'open-uri'

get_url = gets

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

Can anyone tell me what am I doing wrong? I tries looking on google too but no straight answers.


Solution

  • gets adds a new line character to the end of the string. I have used chomp on the gets to remove this below.

    It should work now

    require 'nokogiri'
    require 'open-uri'
    
    get_url = gets.chomp
    
    doc = Nokogiri::HTML(open(get_url))
    puts doc