ruby - Script to append files -


i trying write script following:

there 2 directories , b. in directory a, there files called "today" , "today1". in directory b, there 3 files called "today", "today1" , "otherfile".

i want loop on files in directory , append files have similar names in directory b files in directory a.

i wrote method below handle not sure if on track or if there more straightforward way handle such case?

please note running script directory b.

def append_data_to_daily_files   directory = "b"   dir.entries('b').each |file|     filename = file     next if file == '.' or file == '..'     file.open(file.join(directory, file), 'a') {|file|       dir.entries('.').each |item|         next if !(item.match(/filename/))         file.open(item, "r")         file<<item         item.close       end       #file.puts "hello"       file.close     }   end end 

in opinion, append_data_to_daily_files() method trying many things -- makes difficult reason about. break down logic small steps, , write simple method each step. here's start along path.

require 'set'  def dir_entries(dir)   dir.chdir(dir) {     return dir.glob('*').to_set   } end  def append_file_content(target, source)   file.open(target, 'a') { |fh|     fh.write(io.read(source))   } end  def append_common_files(target_dir, source_dir)   ts = dir_entries(target_dir)   ss = dir_entries(source_dir)   common_files = ts.intersection(ss)    common_files.each |file_name|     t = file.join(target_dir, file_name)     s = file.join(source_dir, file_name)     append_file_content(t, s)   end end  # run script this: #   ruby my_script.rb b     append_common_files(*argv) 

by using set, can figure out common files. using glob can avoid hassle of filtering out dot-directories. designing code take directory names command line (rather hard-coding names in script), end potentially re-usable tool.


Comments