ruby remove unsafe file characters
def remove_unsafe_characters(filename)
safe_characters = /[^\w\s\d.-]/
filename.gsub(safe_characters, '_')
end
Explanation:
def remove_unsafe_characters(filename)
: This line defines a method namedremove_unsafe_characters
that takes afilename
as an argument.safe_characters = /[^\w\s\d.-]/
: This line creates a regular expressionsafe_characters
that matches any character that is not a word character (\w
), whitespace character (\s
), digit (\d
), period (.
), or hyphen (-
).filename.gsub(safe_characters, '_')
: This line uses thegsub
method to replace any unsafe characters in thefilename
string with an underscore (_
). Thegsub
method scans the string for matches to thesafe_characters
regex and replaces them with underscores. The modified filename is then returned as the result of the method.