ruby remove unsafe file characters

def remove_unsafe_characters(filename)
  safe_characters = /[^\w\s\d.-]/
  filename.gsub(safe_characters, '_')
end

Explanation:

  1. def remove_unsafe_characters(filename): This line defines a method named remove_unsafe_characters that takes a filename as an argument.

  2. safe_characters = /[^\w\s\d.-]/: This line creates a regular expression safe_characters that matches any character that is not a word character (\w), whitespace character (\s), digit (\d), period (.), or hyphen (-).

  3. filename.gsub(safe_characters, '_'): This line uses the gsub method to replace any unsafe characters in the filename string with an underscore (_). The gsub method scans the string for matches to the safe_characters regex and replaces them with underscores. The modified filename is then returned as the result of the method.