1

我有代码:

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'

为什么会出现此错误,我该如何解决?

4

1 回答 1

2

String.sub!方法将字符串替换到位,因此除了设置之外还add.sub!(/http:\/\//, "")更改了 的值。addadded

要将open(name)方法与 URI 一起使用, 的值name必须以 URI 方案开头,例如http://.

如果要设置added,请这样做:

added = add.sub(/http:\/\//, "")
于 2012-04-10T01:40:30.590 回答