简体   繁体   中英

Ruby - Find a file by name in a folder

The situation is that there is a folder with some files (eg "1", "2", "3") and I need to request information about this file. One of the options is File.exists?, but it only searches by a strictly defined file name. In turn, I need to search for the required file by query from the input field, ie the name of the file is a variable that the user sets. Can you please tell me the best way to search for a file in a folder in this case?

I think what you want is something like this:

#!/bin/ruby

puts "What file are you looking for?"
filename = gets.chomp 

if File.exists? filename
  puts "File found! :)" 
  # do something else
else
  puts "File not found! :("
  # maybe do something else
end

It will take the user input and then determine if it the file exists with that name (exact match only).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM