From: "David A. Black" Date: 2004-12-17T04:04:16+09:00 Subject: Re: string to (valid) filename Hi -- On Fri, 17 Dec 2004, Julius Plenz wrote: > * itsme213 [2004-12-16]: >> Don't know much about regexes or File/FileUtils, and am a bit stuck >> on what might be quite simple: > > As I obtain from http://www.rubycentral.com/ref/, there are no such > methods defined in File, FileTest or File::Stat. > >> Is there a simple way to create a valid filename (develop on XP, but >> would like the filenames to be valid at least on *nix as well) from >> a string that might contain several platform-illegal filename >> characters. The conversion could change spaces etc. to '_'. >> >> e.g. >> "Animals: Fox, Wolf, and Bear".to_filename >> #=> "animals_fox_wolf_and_bear" > > You could write your own: > > class String > def to_filename > self.to_s.downcase.tr(" ", "_").gsub(/[^\w_\.\-]+/, "") > end > end You could trim that down a little; you don't really need "self.to_s" for a string :-) So: downcase.tr(" ", "_").gsub(/[^\w.-]/, "") or something like that. But I don't think "to_filename" is a good name. In Linux and (I think) any *nix system, "Animals: Fox, Wolf, and Bear" is a perfectly valid filename. So another method name might be better. David -- David A. Black dblack@wobblini.net