何时使用新变量vs字符串插值?

时间:2012-03-28 19:32:25

标签: ruby coding-style refactoring dry

我写了一个脚本,我决定重构,所以我可以添加功能,因为我的同事会想到它。我只努力保存了四行,但主要的变化是我删除了两种方法并减少了调用变量的数量,有利于字符串插值/操作。对此有偏好吗?声明一个新变量只是为了使用一次是否更好,或者在你需要使用它时对字符串进行细微调整是否更加干?例如,这里是原始代码:

def validate_directory(dir)
    puts "Enter the full directory path of the flv files." unless dir
    input =  dir || gets.chomp
    input.gsub!('\\', '/')
    input += '/' unless input[-1..-1] == '/'
    until File.directory?(input) && Dir.glob("#{input}*.flv") != []
        puts "That directory either doesn't exist or contains no .flv files. \nEnter the full directory path of the flv files."
        input = $stdin.gets.chomp
        input.gsub!('\\', '/')
        input += '/' unless input[-1..-1] == '/'
    end
    dir = input
end

def output(flv, location)
    title = flv.dup.gsub!(".flv", ".html")
    vid = flv.dup
    vid.slice!(0..6)
    body = $EMBED.gsub("sample.flv", vid) 
    htmlOutput = File.open(title, "w")
        htmlOutput.write(body)
    htmlOutput.close
    linkList = File.open("#{location}List of Links.txt", "a")
        linkList.write($BASE + vid.gsub(".flv", ".html") + "\n")
    linkList.close
    puts "Files created successfully."
end

dir = ARGV[0].dup unless ARGV.empty?        
folder = validate_directory(dir)            
files = folder.clone + "*.flv"              
flvs = Dir.glob("#{files}") 
File.delete("#{folder}List of Links.txt") if File.exists?("#{folder}List of Links.txt")
flvs.each { |flv| output(flv, folder) }

新的东西:

flash_folder = ARGV[0].dup unless ARGV.empty?

if !flash_folder
  puts "Enter the full directory path of the flv files."
  flash_folder = gets.chomp
end

flash_folder.gsub!('\\', '/')
flash_folder += '/' unless flash_folder[-1..-1] == '/'
until File.directory?(flash_folder) && Dir.glob("#{flash_folder}*.flv") != []
  puts "That directory either doesn't exist or contains no .flv files. \nEnter the full directory path of the flv files."
  flash_folder = $stdin.gets.chomp
  flash_folder.gsub!('\\', '/')
  flash_folder += '/' unless flash_folder[-1..-1] == '/'
end

flash_files = Dir.glob("#{flash_folder}*.flv")

File.delete("#{flash_folder}List of Links.txt") if File.exists?("#{flash_folder}List of Links.txt")

flash_files.each do |flv|
  html_output = File.open("#{flv.gsub(".flv", ".html")}", "w")
    html_output.write("#{embed_code.gsub("sample.flv", flv.slice(7..flv.length))}")
  html_output.close
  link_list = File.open("#{flash_folder}List of Links.txt", "a")
    link_list.write("#{flash_url}#{flv.slice(2..flv.length).gsub(".flv", ".html")}\n")
  link_list.close
end

puts "Finished."

0 个答案:

没有答案