voltas
voltas

Reputation: 563

Ruby unable to create directories

I'm trying to read a file having string values, line by line and create respective folder/directory for every string value.

#require 'fileutils'

value=File.open('D:\\exercise\\list.txt').read
value.gsub!(/\r\n?/, "\n")
value.each_line do |line|
    line.chomp
    print "FOlder names:#{line}"
    Dir.mkdir("D:\\exercise\\#{line}")
end

and I'm getting the below error:

read_folders_svn.rb:8:in `mkdir': Invalid argument - Australia (Errno::EINVAL)
        from read_folders_svn.rb:8:in `block in <main>'

list.txt file's content below

Australia
USA
EUrope
Africa
ANtartica

I tried printing the values and its working fine, while creating the respective directories facing the above issue and even tried using fileutils (fileutils.mkdir) option but still the same issue.

Any suggestions please. Thanks

Upvotes: 1

Views: 255

Answers (2)

Engr. Hasanuzzaman Sumon
Engr. Hasanuzzaman Sumon

Reputation: 2183

Have you checked that the line doesn't contain extra characters? Where line.chomp! will solve your problem but line.strip! is probably the more robust variant, esp if you have windows line-endings of \r\n.

Difference between chomp and strip

String#chomp operates on the end of strings, while String#strip operates on the start and end of strings. String#chomp takes an optional 'record separator' argument, while String#strip takes no arguments. If String#chomp is given no arguments it will remove carriage returns characters from the end of the string being operated on (\r, \n or \r\n). If String#chomp is passed a string as an argument, that string is removed from the end of the string being operated on. String#strip will remove leading and trailing null and whitespace characters from the string being operated on.

"Cadel Evans".chomp(' Evans') # => "Cadel"

"Cadel Evans\r\n".chomp # => "Cadel Evans"

"\tRobbie McEwen\r\n".strip # => "Robbie McEwen"

Upvotes: 4

axiac
axiac

Reputation: 72177

The error is in the line:

line.chomp

It strips the newline from the tail of line and returns a value that is ignored. It doesn't change the value of line. It still ends with "\n" and this is a character that is not allowed in file names on Windows. The code runs fine on Linux and creates directories whose names end in "\n".

The solution is also simple. Use #chomp! instead:

#require 'fileutils'

value=File.open('D:\\exercise\\list.txt').read
value.gsub!(/\r\n?/, "\n")
value.each_line do |line|
    line.chomp!
    print "FOlder names:#{line}"
    Dir.mkdir("D:\\exercise\\#{line}")
end

(It might still produce errors, however, because of empty lines in the input).

Upvotes: 5

Related Questions