I'm trying to write a script that removes temporary files (ie. files with a tilde at the end: temp.txt~)

#!/usr/bin/ruby
system("rm *~") if File::exists?( "*~" );

but that literally looks for files named *~.

I tried something like this:

#!/usr/bin/ruby                                                                                                                                                                                                  
if File::exists?( /\w*~/ )
  puts "Temp exists\n";
else
  puts "Temp doesn't exist\n";
end

but that gives me this:

in `exists?': can't convert Regexp into String (TypeError)

How should I correctly search and remove these files?

I can't say that this is "correct', but this is the way I'd approach the problem. :)

#!/usr/bin/ruby

def yes_no(question)
    print question
    
    if gets.chomp =~ /^[yY]/
        return true
    else
       return false
    end
end

delete_list = []

Dir.new(".").each do |file|
    if file =~ /\w+\~/
        delete_list << file
    end
end

puts delete_list.join("\n")
puts '---------------'
if yes_no("delete the previous files? <y/n>: ")
    delete_list.each { |file| File.delete(file) }
end
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.