[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

string to (valid) filename

Its Me

12/16/2004 6:09:00 PM

Don't know much about regexes or File/FileUtils, and am a bit stuck on what
might be quite simple:

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"

Thanks


5 Answers

Julius Plenz

12/16/2004 6:48:00 PM

0

* itsme213 <itsme213@hotmail.com> [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.rubycentra..., 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

Julius
--
p"ispp\e[ggk^Zf\23dfRh\16UMNUNZ".unpack("C*").map{|c|@i||=0;c+@i+=1}.pack("C*")

dblack

12/16/2004 7:04:00 PM

0

William James

12/16/2004 7:38:00 PM

0

self.downcase.gsub( /[^-\w\.]+/, "_" )

Charles Mills

12/16/2004 9:37:00 PM

0

If you don't like regexp you could use String#tr and String#delete.

$ ruby -e 'puts "Animals: Fox, Wolf, and Bear".delete(",:").tr("
","_")'
Animals_Fox_Wolf_and_Bear
$ ruby -e 'puts "Animals: Fox, Wolf, and
Bear".downcase.delete(",:").tr(" ","_")'
animals_fox_wolf_and_bear

You'll probably have to put more characters in #delete's argument
string.

Learning about regexps is worth the effort.

-Charlie

Its Me

12/16/2004 9:41:00 PM

0

> Learning about regexps is worth the effort.

You are right, I intend to. Just needed to get a quick working version of
this.