2012-04-10 74 views
1

我的代碼:開放-URI紅寶石錯誤

require 'open-uri' 
print "Enter a URL: " 
add = gets 
added = add.sub!(/http:\/\//, "") 
puts "Info from: #{add}" 
open("#{add}") do |f| 
    img = f.read.scan(/<img/) 
    img = img.length 
    puts "\t#{img} images" 
    f.close 
end 
open("#{add}") do |f| 
    links = f.read.scan(/<a/) 
    links = links.length 
    puts "\t#{links} links" 
    f.close 
end 
open("#{add}") do |f| 
    div = f.read.scan(/<div/) 
    div = div.le1ngth 
    puts "\t#{div} div tags" 
    f.close 
end 

(是的,我知道這是不好的代碼,它請不要評論)當我運行它,併爲URL ,我進去,說:

http://stackoverflow.com 

我得到以下錯誤:

/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/open-uri.rb:32:in `initialize': No such file or directory - http (Errno::ENOENT) 
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/open-uri.rb:32:in `open_uri_original_open' 
    from /System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/open-uri.rb:32:in `open' 

爲什麼會出現這種錯誤來了,我該如何解決?

回答

2

String.sub!方法替換代替字符串,所以add.sub!(/http:\/\//, "")另外改變的add值來設定added

要使用帶有URI的open(name)方法,name的值必須以URI方案開頭,如http://

如果你想設置added,這樣做就像這樣:

added = add.sub(/http:\/\//, "")