From: Robert Klemme Date: 2007-11-26T16:34:53+09:00 Subject: Re: Moving files matching Regex 2007/11/25, Raul Parolari : > Robert Klemme wrote: > > > I would not do that because it is not really an Array operation. > > You are right; it does not belong in class Array. > > > Having a top level method (aka function) is better IMHO. > > Here I use the occasion to share a perplexity I have, when I look at > Ruby programs, and I sometimes see a myriad of top-level methods. If I > ask the reason, the answer is a vague "they do not really fit well > anywhere", which leaves me a bit disconcerted (especially when the > script is part of a project that may grow, not something written to be > used once). > > In the case discussed, I would place this method in a module (that would > just need to be required): > > module MyUtils > def self.mv_files_to_subdir(files, subdir) > files.each do |curr_file| > .. > end > end > end > > or, as this is in fact a file operation, I would consider to reopen > FileUtils and add the method: > > #-- > module FileUtils > def self.mv_files_to_subdir(files, subdir) > files.each do |curr_file| > new_file = "./#{subdir}/#{curr_file}" > FileUtils.mv(curr_file, new_file) unless File.exists?(new_file) > end > end > end > > fglob= %r{^ (CAL|NCPH|GOH) \d{6} \.xls $}x > all_files = Dir.glob("*") > my_files = all_files.grep(fglob) > > FileUtils.mv_files_to_subdir(my_files, 'sent') > #------- > > It is a small point (some may say 'but what's the difference with a > top-level method?'), but let me know your opinion, if you have a chance Definitively the right way to go if there is a chance that the code is reused and might create namespace collisions in a larger project. If if is just used in a simple script I would stick with the top level method defined inside the script because distributing the code would be unnecessarily complex in that case. One can refactor later if needed. Kind regards robert -- use.inject do |as, often| as.you_can - without end