I have this ruby script that allows me to enter the name of a pdf file which will then look for the file in a folder and open it up. Except I have to be pretty precise about my input. For example:
Enter the name of the pdf file you would like to open.
> Survival Manual
The above line opens the book if the file is named exactly as I typed it, but lets say I want to just type
> Survival
It won’t open it up. So I have the following code:
docs = Dir.entries("/Documents") #=> ["Survival Manual.pdf", "Military Manual.pdf"]
input = gets.chomp #=> "Survival"
select_doc = docs.grep(Regexp.new(input)) #=> ["Survival Manual.pdf"]
system("open", "/Documents/#{select_doc[0]}")
And the last line finally opens the pdf. This code seems convoluted and I know it can be done a lot better and if so, is there something I’m missing? Could I have used better methods? After several attempts to refactor this code it seemed like it only got worse. Ruby is great language I’d like to be able to do things right, and maybe those new to ruby (like me) can take something from this. Thanks in advance.
1 Answer