Forum: Ruby Error opening a file when filename is passed thru a variable

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
E0d56582d53eee6617ad847390c0799c?d=identicon&s=25 Raju Alluri (avr_1)
on 2008-11-21 21:41
Hi, I have a script as below. Can you please tell me if something is
wrong here ?
It errors out for this code where as if I pass full name instead of
variable, it is working.

cat readfile5.rb
#!/usr/bin/env ruby
logfiledir = "/apollo/env/A9AdamAdProxy/var/output/logs"
filename = `ls -t #{logfiledir} | grep service_log | head -1`
fullfilename = logfiledir + "/" + filename
puts "Full name of the file is #{fullfilename}"
file = File.new("#{fullfilename}", "r")
data = ''
   while (line = file.gets)
        data += line if line =~ /START/ .. line =~ /EOE/
   end
   file.close

ERROR:
readfile5.rb:6:in `initialize': No such file or directory -
/apollo/env/A9AdamAdProxy/var/output/logs/service_log.2008-11-21-20
(Errno::ENOENT)
        from readfile5.rb:6:in `new'
        from readfile5.rb:6

Thanks,
Raju
40613e55d7082e5f08429dfb50d0680e?d=identicon&s=25 Stefan Lang (Guest)
on 2008-11-22 11:56
(Received via mailing list)
2008/11/21 Raju Alluri <avr_1@yahoo.com>:
> Hi, I have a script as below. Can you please tell me if something is
> wrong here ?
> It errors out for this code where as if I pass full name instead of
> variable, it is working.
>
> cat readfile5.rb
> #!/usr/bin/env ruby
> logfiledir = "/apollo/env/A9AdamAdProxy/var/output/logs"
> filename = `ls -t #{logfiledir} | grep service_log | head -1`

I suspect that the command returns a string that ends in a
newline character. Try adding:

    filename.chomp!

> fullfilename = logfiledir + "/" + filename
> puts "Full name of the file is #{fullfilename}"

When debugging such stuff, it's always a good
idea to use #inspect for strings:

    puts "Full name of the file is #{fullfilename.inspect}"

> (Errno::ENOENT)
>        from readfile5.rb:6:in `new'
>        from readfile5.rb:6
>
> Thanks,
> Raju

Stefan
This topic is locked and can not be replied to.