我有代码:
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'
为什么会出现此错误,我该如何解决?
答案 0 :(得分:2)
String.sub!
方法会替换现有字符串,因此add.sub!(/http:\/\//, "")
除了设置add
之外,还会更改added
的值。
要将open(name)
方法用于URI,name
的值必须以URI方案开头,例如http://
。
如果您想设置added
,请执行以下操作:
added = add.sub(/http:\/\//, "")