Environment: Ruby 1.9.2, Rails 3.0.3, Ubuntu
When I try to open a URL using:
open("http://www.cnn.com")
I get the following error:
Errno::ENOENT: No such file or directory - http://www.cnn.com
from (irb):9:in `initialize'
from (irb):9:in `o开发者_运维技巧pen'
from (irb):9
(It's a difficult topic to search). This is happening in both irb and in my app. It used to work under Ruby 1.8.7 and Rails 2.3.4 but it appears that something has changed.
I can reproduce the error if I try
open('http://www.google.com')
I'll get this error: `initialize': No such file or directory - http://www.google.com (Errno::ENOENT)
Instead, I required 'open-uri' in ruby 1.9.2 and it worked -
require 'open-uri'
url = URI.parse('http://www.google.com')
open(url) do |http|
response = http.read
puts "response: #{response.inspect}"
end
I tried something like this in Codecademy's exercise section. Turns out that the request wanted a closing backslash. Evidently open('http://google.com/')
went through fine where open('http://google.com')
did not.
I can't reproduce the error, in 1.8.7 I get a File object and in 1.9.2 I get a StringIO object. My guess is that some other code is overriding that functionality. Maybe you can try using the Net::HTTP object instead:
require 'net/http'
require 'uri'
Net::HTTP.get_print URI.parse('http://www.cnn.com')
or
require 'net/http'
require 'uri'
url = URI.parse('http://www.cnn.com')
res = Net::HTTP.start(url.host, url.port) {|http|
http.get('/')
}
puts res.body
精彩评论