在这个程序中,我在硬盘上寻找一个文件,通过名称,扩展名,名称和扩展名来选择,直到代码变大,我想知道如何减少一点。 如何减少 Ruby 中的条件行数? 在 Ruby 中减少以下情况的最佳方法是什么?
require "colorize"
new_name_file = {}
loop do
puts
puts "Will we search for the file by name(1), extension(2), name extension(3) or exit programm(4)?"
print "\n>>>>>> ".magenta
name_extension = gets.to_i
if name_extension == 1 # =========== search file name =================
puts "Enter file name (test, lesson, ruby....etc.) "
print "\n>>>>>> ".cyan
file_name = gets.strip.downcase
puts "Name the hard drive on which we will search for the file(C, D, E, F....e.t.c.): "
print "\n>>>>>> ".green
hdd_search = gets.strip.capitalize
# search file hdd
contents = Dir.glob("#{hdd_search}:/**/#{file_name}.*")
elsif name_extension == 2 # ========= search by file extension =============
puts "Enter file extension(txt, rb, jpg, csv, json) "
print "\n>>>>>> ".cyan
file_extension = gets.strip.downcase
# on which drive we will search put the letter
puts "Name the hard drive on which we will search for the file(C, D, E, F....e.t.c.): "
print "\n>>>>>> ".green
hdd_search = gets.strip.capitalize
# search file hdd
contents = Dir.glob("#{hdd_search}:/**/*.#{file_extension}")
elsif name_extension == 3 # ========= search by name and file extension =============
puts "Enter a name and file extension(test.txt, test.rb, test.jpg, test.csv, test.json..etc) "
print "\n>>>>>> ".cyan
file_extension_name = gets.strip
# on which drive we will search put the letter
puts "Name the hard drive on which we will search for the file(C, D, E, F....e.t.c.): "
print "\n>>>>>> ".green
hdd_search = gets.strip.capitalize
# search file hdd
contents = Dir.glob("#{hdd_search}:/**/#{file_extension_name}")
elsif name_extension == 4
puts "Exit programm".red
exit
end
contents.each do |txt_name|
z_name = File.basename(txt_name) # file name
path = File.expand_path(txt_name) # path file
new_name_file[z_name] = path # everything in the hash
end
new_name_file.each do |k, v| # hash output
puts "file : ".cyan + "#{k} " + " path:".cyan + "#{v}"
end
end
最佳答案
您可以将代码包装在方法中的条件内:
def process_file(file_types)
puts "Enter file name (#{file_types.join(',')}....etc.) "
print "\n>>>>>> ".cyan
file_name = gets.strip.downcase
puts "Name the hard drive on which we will search for the file(C, D, E, F....e.t.c.): "
print "\n>>>>>> ".green
hdd_search = gets.strip.capitalize
# search file hdd
contents = Dir.glob("#{hdd_search}:/**/#{file_name}.*")
end
file_types = {
"1" => ['test', 'lesson', 'ruby']
"2" =>
}
loop do
puts
puts "Will we search for the file by name(1), extension(2), name extension(3) or exit programm(4)?"
print "\n>>>>>> ".magenta
name_extension = gets
if name_extension == '4'
puts "Exit programm".red
exit
end
process_file(file_types[name_extension])
end
关于ruby - 如何减少 Ruby 的 if 条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57616197/