Woulf Alpha
Woulf Alpha

Reputation: 41

Use a string to filename

I'm trying to put the filename from a string, but can not.

This works well:

#!/usr/bin/ruby
require 'httpclient'

http2 = HTTPClient.new
response = http2.get_content("http://example.com/version.ini")

response.each_line do | line |

    http = HTTPClient.new
    my_file = open('file.zip', 'wb')
    my_file.write(http.get_content("http://example.com/data.zip"))

end

puts "Done."

But this not:

#!/usr/bin/ruby
require 'httpclient'

http2 = HTTPClient.new
response = http2.get_content("http://example.com/version.ini")

response.each_line do | line |
    puts line # -> file.zip
    http = HTTPClient.new
    my_file = open(line, 'wb')
    my_file.write(http.get_content("http://example.com/data.zip"))

end

puts "Done."

Console:

C:/Ruby22-x64/lib/ruby/2.2.0/open-uri.rb:36:in initialize': Invalid argument @ rb_sysopen - file.zip (Errno::EINVAL) from C:/Ruby22-x64/lib/ruby/2.2.0/open-uri.rb:36:inopen' from C:/Ruby22-x64/lib/ruby/2.2.0/open-uri.rb:36:in open' from launcher.rb:10:inblock in ' from launcher.rb:7:in each_line' from launcher.rb:7:in'

Upvotes: 4

Views: 232

Answers (1)

Wand Maker
Wand Maker

Reputation: 18762

Issue is with newline char, try stripping it.

my_file = open(line.chomp, 'wb')

Upvotes: 1

Related Questions