Pan7h3r
Pan7h3r

Reputation: 5

Ruby: How to delete files and folders under C:\Users\ for specified Username

Basically I want to create a program that can delete 3 directories and a file in preparation for a software's "Rebuild" that needs to be done every so often for troubleshooting purposes.

The problem is, it needs to be used on multiple computers with different users and originally I just had a batch program that I would have to edit the corresponding username into. I'm trying to automate this.

How can I make it so that what's entered for Username gets put in the FileUtils.rm_rf path? I tried doing ${Username} #{Username} and @{Username}, none of them seemed to work?

Also how can I make it so if the specific file isn't found it will return a custom message instead of a ruby error?

Thanks in advance! and sorry for my noobness, this is my first post and I am VERY new to ruby (I even googled how to use 'goto' in ruby!)

require 'fileutils'
puts "Please enter in your username:"
Username = gets.chomp
def question?
    puts "Are you sure you want to continue? (Y/N)"
    case gets.strip
    when 'Y', 'y', 'yes' 'Yes'
        FileUtils.rm_rf('C:\Users\USERNAME')
        FileUtils.rm_rf('C:\Users\USERNAME')
        FileUtils.rm_rf('C:\Users\USERNAME')
        File.delete('C:\Users\USERNAME\file.txt')
        puts "Files Successfully deleted"
        sleep(5)
        exit
    when 'N', 'n', 'No', 'no'
        exit
    else
        puts "Invalid Character!"
        question?
    end
end
question?

Upvotes: 0

Views: 254

Answers (1)

bjhaid
bjhaid

Reputation: 9762

change this:

require 'fileutils'
puts "Please enter in your username:"
Username = gets.chomp
def question?
    puts "Are you sure you want to continue? (Y/N)"
    case gets.strip
    when 'Y', 'y', 'yes' 'Yes'
        FileUtils.rm_rf('C:\Users\USERNAME')
        FileUtils.rm_rf('C:\Users\USERNAME')
        FileUtils.rm_rf('C:\Users\USERNAME')
        File.delete('C:\Users\USERNAME\file.txt')
        puts "Files Successfully deleted"
        sleep(5)
        exit
    when 'N', 'n', 'No', 'no'
        exit
    else
        puts "Invalid Character!"
        question?
    end
end

to:

  require 'fileutils'
  def question?
    puts "Please enter in your username:"
    username = gets.chomp
    puts "Are you sure you want to continue? (Y/N)"
    case gets.strip
    when 'Y', 'y', 'yes' 'Yes'
        FileUtils.rm_rf("C:/Users/#{username}")
        File.delete("C:/Users/#{username}/file.txt") #I doubt you need this line
        puts "Files Successfully deleted"
        sleep(5)
        exit
    when 'N', 'n', 'No', 'no'
        exit
    else
        puts "Invalid Character!"
        question?
    end
  end

You can only interpolate variables in double_quoted strings, you want to have your variables username in the scope of your method question?

Upvotes: 1

Related Questions