title: How can I copy files and rename them according to their origin directories using Ruby?
body: <p>I have many directories with generically named txt files inside.  I want to make copies of the txt files, rename them according to the containing directory of each, then move them to the parent directory (that being the directory that holds the directories that hold the original txt files, designated "txts" in the script below).  I want to retain the original txt files with their original names in their original directories as well so that nothing within the original directories changes.</p>
  
  <p>I have an old script that I think achieved (some of) my goals once, perhaps moving instead of copying the original txt files, but I'm unable to run it successfully now:</p>
  
  <pre><code>require 'find'
  require 'fileutils'
  
  Find.find("txts") do |path|
    if FileTest.directory?(path)
      next
    end
  
    ret = path.scan(/.*txts\/([^\/]+)\/.*/)
    name = ret[0].to_s + ".txt"
    FileUtils.mv(path, name)
  end
  </code></pre>
  
  <p>Years ago a friend wrote this and ran it from within a unix environment with success.  When I run it now, an enormous number of errors are returned.  I'm using Ruby 2.2.2 and it's entirely possible there's a placeholder somewhere that I'm too newbish to recognize, or perhaps something changed from the older version of FileUtils...  I truly have no idea and am afraid I've been unable to turn up any answers with my neophyte skills.</p>
  
  <p>And so I appeal to you...</p>
  
  <p>Edit: Here's the error message:</p>
  
  <pre><code>C:/Ruby22/lib/ruby/2.2.0/fileutils.rb:1328:in `stat': Invalid argument @ rb_file
  _s_stat - ["may2013"].txt (Errno::EINVAL)
          from C:/Ruby22/lib/ruby/2.2.0/fileutils.rb:1328:in `lstat'
          from C:/Ruby22/lib/ruby/2.2.0/fileutils.rb:1247:in `exist?'
          from C:/Ruby22/lib/ruby/2.2.0/fileutils.rb:519:in `block in mv'
          from C:/Ruby22/lib/ruby/2.2.0/fileutils.rb:1570:in `block in fu_each_src
  _dest'
          from C:/Ruby22/lib/ruby/2.2.0/fileutils.rb:1586:in `fu_each_src_dest0'
          from C:/Ruby22/lib/ruby/2.2.0/fileutils.rb:1568:in `fu_each_src_dest'
          from C:/Ruby22/lib/ruby/2.2.0/fileutils.rb:516:in `mv'
          from extracttxt.rb:12:in `block in &lt;main&gt;'
          from C:/Ruby22/lib/ruby/2.2.0/find.rb:48:in `block (2 levels) in find'
          from C:/Ruby22/lib/ruby/2.2.0/find.rb:47:in `catch'
          from C:/Ruby22/lib/ruby/2.2.0/find.rb:47:in `block in find'
          from C:/Ruby22/lib/ruby/2.2.0/find.rb:42:in `each'
          from C:/Ruby22/lib/ruby/2.2.0/find.rb:42:in `find'
          from extracttxt.rb:6:in `&lt;main&gt;'
  </code></pre>