[lnkForumImage]
TotalShareware - Download Free Software

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


 

Forums >

comp.lang.ruby

renaming files randomly

Bil Kleb

7/9/2006 2:54:00 PM

Got this request yesterday and still haven't had
time to decipher it and code it -- I figured I'd
throw it out here and see what you folks come up with:

Eric wrote:
>
> I want to change the names of several hundred files to random numbers
> (without overwriting any files). I have a bunch of pictures for our
> reception, but they're basically in chronological order by their current
> filenames. But I want the slideshow to play in random order, so I need to
> randomize the filenames.

I'll also ask why the slideshow software can't just be
told to show things randomly...

Thanks,
--
Bil
http://fun3d.lar...
8 Answers

dblack

7/9/2006 3:17:00 PM

0

Ara.T.Howard

7/9/2006 3:28:00 PM

0

Ara.T.Howard

7/9/2006 3:35:00 PM

0

Ara.T.Howard

7/9/2006 3:42:00 PM

0

dblack

7/9/2006 3:50:00 PM

0

Bil Kleb

7/9/2006 3:54:00 PM

0

dblack@wobblini.net wrote:
>
> Dir.chdir("photos") do
> files = Dir["*"]
> new_names = [*0...files.size].sort_by { rand }
> files.zip(new_names).each do |f,n|
> File.rename(f, n.to_s)
> end
> end

Thanks David.

I'll push that over and see what comes back.

Also, thanks for showing "zip" in action -- I just
learned about that one a couple months ago and hadn't
figured out a place to use it yet.

Regards,
--
Bil
http://fun3d.lar...

ToRA

7/9/2006 6:10:00 PM

0

Hey,

You could rewrite without the zip and the temporary variable...
ala:

Dir.chdir("photos") do
Dir["*"].sort_by{rand}.each_with_index do |f,n|
File.rename(f, n.to_s)
end
end

Though be careful, you've just lost the file-name extension, and
unpretty things could happen if you run the script over the same
directory multiple times (which I guess could happen when you want to
re-shuffle the playlist).

Regards,

Tris

Marcel Molina Jr.

7/9/2006 6:16:00 PM

0

On Mon, Jul 10, 2006 at 01:05:06AM +0900, Bil Kleb wrote:
> dblack@wobblini.net wrote:
> >
> > Dir.chdir("photos") do
> > files = Dir["*"]
> > new_names = [*0...files.size].sort_by { rand }
> > files.zip(new_names).each do |f,n|
> > File.rename(f, n.to_s)
> > end
> > end
>
> Thanks David.
>
> I'll push that over and see what comes back.
>
> Also, thanks for showing "zip" in action -- I just
> learned about that one a couple months ago and hadn't
> figured out a place to use it yet.

One useful use of zip is transformation two arrays into hash pairs:

> Hash[*%w(a b c d).zip([1, 2, 3, 4]).flatten]
=> {"a"=>1, "b"=>2, "c"=>3, "d"=>4}

marcel
--
Marcel Molina Jr. <marcel@vernix.org>