Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No such file or directory @ rb_sysopen ruby

Tags:

ruby

Facing below issue eventhough the file is present in the folder.

H:\Ruby_test_works>ruby hurrah.rb
hurrah.rb:7:in `read': No such file or directory @ rb_sysopen - H:/Ruby_
test_works/SVNFolders.txt (Errno::ENOENT)
        from hurrah.rb:7:in `block in <main>'
        from hurrah.rb:4:in `each_line'
        from hurrah.rb:4:in `<main>'

Input file (input.txt) Columns are tab separated.

10.3.2.021.asd  10.3.2.041.def  SVNFolders.txt
SubversionNotify    Subversionweelta    post-commit.bat
Commit message  still rake  customemail.txt
mckechney.com   yahoo.in    ReadMe.txt

Code :

dir = 'H:/Ruby_test_works'
file = File.open("#{dir}/input.txt", "r")

file.each_line do |line|
  initial, final, file_name = line.split("\t")
  #puts file_name
  old_value = File.read("#{dir}/#{file_name}")

  replace = old_value.gsub( /#{Regexp.escape(initial)}, #{Regexp.escape(final)}/)
  File.open("#{dir}/#{file_name}", "w") { |fi| fi.puts replace }

end

I have tried using both forward and backward slashes but no luck. What I'm missing, not sure. Thanks.

puts file_name gives the below values

SVNFolders.txt
post-commit.bat
customemail.txt
ReadMe.txt
like image 822
Goku Avatar asked Jun 21 '17 14:06

Goku


1 Answers

The file_name contains the newline character \n at the end, which won't get printed but messes up the path. You can fix the issue by stripping the line first:

initial, final, file_name = line.strip.split("\t")

When debugging code, be careful with puts. Quoting its documentation reveals an ugly truth:

Writes the given object(s) to ios. Writes a newline after any that do not already end with a newline sequence.

Another way to put this is to say it ignores (potential) newlines at the end of the object(s). Which is why you never saw that the file name actually was SVNFolders.txt\n.

Instead of using puts, you can use p when troubleshooting issues. The very short comparison between the two is that puts calls to_s and adds a newline, while p calls inspect on the object. Here is a bit more details about the differences: http://www.garethrees.co.uk/2013/05/04/p-vs-puts-vs-print-in-ruby/

like image 144
jdno Avatar answered Sep 21 '22 13:09

jdno