Chuck Smithson Chuck Smithson - 17 days ago 5
Ruby Question

Ruby: Rename all files within a user given directory from .txt to text

some help here would be appreciated. The goal is to rename all .txt files to .text from a user entered directory in ruby. I have to use fileutils as a requirement. When I run my current script I do not receive any errors. However, nothing happens either... I'm sure one of you could probably help me pinpoint the issue.

#!/usr/bin/ruby
#This program was written by me
puts “what directory would you like to change? “
require 'fileutils'
pathname = gets.chomp
def rename(pathname)
currentdir = Dir.new('.')
newfile = FileTest.exists?(pathname.to_s)
if pathname != "q"
if newfile == "true"
require 'fileutils'
newfile.each do |f|
FileUtils.mv "#{File.dirname(f)}/#{File.basename(f, '.*')}.txt", "#{File.dirname(f)}/#{File.basename(f,'.*')}.text"
end
elsif currentdir
require 'fileutils'
(currentdir).each do |f|
FileUtils.mv "#{File.dirname(f)}/#{File.basename(f, '.*')}.txt", "#{File.dirname(f)}/#{File.basename(f,'.*')}.text"
end
else
puts "Invalid Path"
end
end
end


This question is different from one of the comments suggested becauset the requirement is to use fileutils and have the user enter the directory they would like to edit. This entry looks for a file name from ANYWHERE and does not use fileutils

Answer

As I understand from Your code,

1) You were not calling rename function

2) Your rename function had unnecessary checking of newfile, currentdir - if You want execute from current dir, it will understand "." symbol and will do glob in current dir.



I've moved pathname != "q" to outside of rename because of rename must do renaming, nothing else.

So final code:

#!/usr/bin/ruby
#This program was written by me

require 'fileutils'

def rename(pathname)
  if File.directory?(pathname.to_s)
    puts "renaming files in path"+pathname.to_s
    Dir.glob(File.dirname(pathname.to_s)+"/*.txt").each do |f|
      FileUtils.mv f, "#{File.dirname(f)}/#{File.basename(f,'.*')}.text"
      puts "#{File.basename} => #{File.basename(f,'.*')}.text"
    end
  else
    puts "Invalid Path" 
  end
end

puts "what directory would you like to change? "
pathname = gets.chomp

if pathname != "q"
  rename(pathname)
end



p.s. normal user will just call:

rename -S .txt .text /path/to/files/*.txt

or:

rename -S .txt .text ./*.txt
Comments