Webtm Webtm - 5 months ago 16
Ruby Question

Passing the contents of a file to FileUtils.cp

file = 'list.txt'
fileArray = []

list_open = File.open(file, "r")
list_open.each_line { |line|
fileArray.push line
}

fileArray.each { |x| puts x }
fileArray.each { |x| FileUtils.cp x, "/home/user/scripts/" }


The contents of
lists.txt
is just a path to a file. I want to read from the file and pass it to
cp
here and copy it to
/home/user/scripts/
.

When I run this script, here is the error I receive:

/usr/local/lib/ruby/2.1/fileutils.rb:1401:in `initialize': No such file or directory @ rb_sysopen - /home/user/test.txt (Errno::ENOENT)
from /usr/local/lib/ruby/2.1/fileutils.rb:1401:in `open'
from /usr/local/lib/ruby/2.1/fileutils.rb:1401:in `copy_file'
from /usr/local/lib/ruby/2.1/fileutils.rb:483:in `copy_file'
from /usr/local/lib/ruby/2.1/fileutils.rb:400:in `block in cp'
from /usr/local/lib/ruby/2.1/fileutils.rb:1579:in `block in fu_each_src_dest'
from /usr/local/lib/ruby/2.1/fileutils.rb:1593:in `fu_each_src_dest0'
from /usr/local/lib/ruby/2.1/fileutils.rb:1577:in `fu_each_src_dest'
from /usr/local/lib/ruby/2.1/fileutils.rb:399:in `cp'
from ./for_Test.rb:12:in `block in <main>'
from ./for_Test.rb:12:in `each'
from ./for_Test.rb:12:in `<main>'

Answer

Recall that each line in a file necessarily ends with a newline ("\n"). You need to remove it, which is easy with String#chomp:

list_path = "list.txt"
filenames = []

File.open(list_path, "r") do |list|
  list.each_line do |line|
    filenames.push(line.chomp)
  end
end

...or more succinctly:

filenames = File.open(list_path, "r") do |list|
  list.each_line.map(&:chomp)
end
Comments