I am trying to check whether a directory entered through the command line contains files with a certain file extension. For example, if I have a folder “Folder1” with another folder in it “Folder 2” and Folder2 contains several files, “test.asm”, “test.vm”, “test.tst”. I am taking either a directory or a file through the command line like this
ruby translator.rb Folder1/Folder2
or
ruby translator.rb Folder1/Folder2/test.vm
What I’m trying to do is error checking. I already have checks for whether the input is a folder and now I need to check whether the folder actually contains a .vm file.
What I’ve done so far is this:
require 'pathname'
pn = Pathname.new(ARGV[0])
if ARGV.size != 1
puts "Proper usage is: ruby vmtranslator.rb file_directory\file.vm \nOR \nruby vmtranslator.rb file_directory\ where file_directory has multiple vm files test".split("\n")
elsif !pn.exist? && !pn.directory?
puts "Something is wrong with the file"
puts "Either try another file or check the file extension"
elsif pn.directory? && pn.children(false).extname.include?('.vm')
puts "this should print if Folder1 is the folder, but not if Folder2 is.."
vm_file1 = File.open("OPEN FILES WITH .vm AS EXTENSION)
elsif pn.exist? || pn.file?
puts "this is right"
vm_file = File.open(ARGV[0], "r")
asm_file = File.new(ARGV[0].sub('.vm', '.asm'), "w")
end
So what that should do is check whether there is only 1 argument first, if so, then it checks if it’s a file or directory else it outputs an error, then what I’m doing is checking if it’s a directory. If so, I need to check if the directory actually contains .vm files. I tried pn.each_child {|f| f.extname == '.vm'} but that only checks the first value before it returns true. Is there any easier way to check the whole array before returning true, other than just setting some boolean?
Some of the code up there isn’t done, I’m just asking if there is any way to check a directory for a file of a certain extension. I can’t find anything with my searches so far.
1 Answer