Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Oct 10

CD-o-matic with Ruby

Posted by Sandro Paganotti in Ruby on Rails - comments are closed digg this add to delicious

With just a bunch of ruby lines I created a small utility that fills a folder with songs picked randomly from a choosen repository until the maximum specified size is reached.

This tool is very useful for me ‘cause I can change my USB player music day-by-day without choosing each song from my repository (which is a boring and extremely long operation).

So, here you are the code:



require "ftools" 

# Path were you want to store the randomly picked music
finalpath = "/Users/sandro/mp3xcd/" 
# Path from which pick the music
repository = "/Volumes/ntfs/Musica/" 
# Size Limit for the 'finalpath' folder (in bytes)
sizetomatch = 650000000

selected = []
cursize = 0
candidates = Dir.glob(repository+"**/*.mp3")

while cursize < sizetomatch do
        nr = rand(candidates.length)
        unless selected.include?(candidates[nr])
                selected << candidates[nr]
                puts "Adding: " + File.basename(candidates[nr])
                cursize += File.size(candidates[nr])
                puts "Space Left: " + (sizetomatch - cursize).to_s + " bytes" 
        end
end

selected.each do |f|
    File.copy(f,finalpath + rand(selected.length).to_s  + "-" +  File.basename(f))
    puts "Copying " + f + " to selected folder " 
end 


Comments

  • EmmanuelOga

    Posted on October 12

    Hi! nice idea. I recommend you to change the "selected = []" to " require 'set' selected= Set.new " Set is implemented based on hash, so now you can know if the songs is already there in logarithmic time instead of linear time of Array.include?. That's all. Now, this script may not need a critical speed burst, but being so easy to change I thing you would like to do it.
  • Sandro

    Posted on October 15

    Hi ! Thanks for the suggest ! I've never heard about Set class; seems pretty cool ! I'll change the post following your comment's advices.
  • sunfast

    Posted on October 20

    nice, I love little examples like this of fun things to do with ruby. Keeps the learning interesting for us newbs.

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory