2

I'm trying to execute a Ruby program (Ruby v2.5.3) on Windows 10 where I basically open a file (sample1.txt, sample2.txt) and append its contents (a list of 3 names) to an empty file (result.txt) and later sort the contents of file result.txt (entire code below). However, when I run this code on RubyMine 2019.1, I get an error as

Traceback (most recent call last):
        6: from C:/Users/tanveer.dey/RubymineProjects/src/Assignment9.rb:5:in `<main>'
        5: from C:/Users/tanveer.dey/RubymineProjects/src/Assignment9.rb:5:in `each'
        4: from C:/Users/tanveer.dey/RubymineProjects/src/Assignment9.rb:7:in `block in <main>'
        3: from C:/Users/tanveer.dey/RubymineProjects/src/Assignment9.rb:7:in `each'
        2: from C:/Users/tanveer.dey/RubymineProjects/src/Assignment9.rb:8:in `block (2 levels) in <main>'
        1: from C:/Users/tanveer.dey/RubymineProjects/src/Assignment9.rb:8:in `open'
C:/Users/tanveer.dey/RubymineProjects/src/Assignment9.rb:8:in `initialize': Permission denied @ rb_sysopen - result.txt (Errno::EACCES)

All files have full permissions. However, when I execute the same code via the IRB terminal it works perfectly fine.

I've just started working on Ruby and I couldn't find the solution to this problem anywhere. Your help is greatly appreciated.

file_array = ["sample1.txt", "sample2.txt"]

file_array.each do |x|
  file = File.open(x,'r')
  file.each do |h|
  open('result.txt', 'a') do |f|
    puts f << h
  end
  end
  open('result.txt','a') do |f|
    puts f << "\n"
  end
  end

new_array = File.readlines('result.txt').sort
File.open('result.txt','w') do |file|
  new_array.each {|n| file.puts(n)}
end
Tanveer Dey
  • 53
  • 1
  • 7

1 Answers1

2

Found the fix! The issue occurs because the file result.txt, to which the contents are being "written" to, is specified "with" the extension (.txt). Removing the extension from the file operations which involves writing solves the issue. Below code without the extension now works perfectly.


file_array.each do |x|
  file = File.open(x,'r')
  file.each do |h|
  open('result', 'a') do |f|
    puts f << h
  end
  end
  open('result','a') do |f|
    puts f << "\n"
  end
  end

new_array = File.readlines('result').sort
File.open('result','w') do |file|
  new_array.each {|n| file.puts(n)}
end
Tanveer Dey
  • 53
  • 1
  • 7