# Error opening a file when filename is passed thru a variable

**URL:** <https://www.ruby-forum.com/t/error-opening-a-file-when-filename-is-passed-thru-a-variable/153851>\
**Category:** Ruby\
**Created:** [November 21, 2008, 9:41pm UTC](https://www.ruby-forum.com/t/error-opening-a-file-when-filename-is-passed-thru-a-variable/153851 "2008-11-21T21:41:57Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![raju\_k](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a9adbd/32.png) [@raju\_k](https://www.ruby-forum.com/u/raju_k)\
**Post date:** [November 21, 2008, 9:41pm UTC](https://www.ruby-forum.com/t/error-opening-a-file-when-filename-is-passed-thru-a-variable/153851/1 "2008-11-21T21:41:57Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![raju\_k](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a9adbd/32.png) [@raju\_k](https://www.ruby-forum.com/u/raju_k)\
**Post date:** [November 22, 2008, 11:56am UTC](https://www.ruby-forum.com/t/error-opening-a-file-when-filename-is-passed-thru-a-variable/153851/2 "2008-11-22T11:56:49Z")

</div>

2008/11/21 Raju A. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

> 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
