O'Reilly logo

Ruby by Example by Kevin C. Baird

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

#38 Better Overnight DJ (radio_player2.rb)

This script, radio_player2.rb, is an improvement on radio_player1.rb. Instead of placeholder Procs, it will actually play sound files, as well as log playback with specific times.

The Code

  #a/usr/bin/env ruby
  # radio_player2.rb


❶ LOG_FILE = '/tmp/radio_player2.log'

❷ PLAYERS = {
    '.mp3' => 'mpg321',
    '.ogg' => 'ogg123',
    ''     => 'ls'
  }

❸ # these are variables, local to Kernel.
  # They work just as well as constants.
  play_file_proc = lambda do |filename|    Callbacks
❹   ext = File.extname(filename)
❺   system("#{PLAYERS[ext]} #{filename}") if PLAYERS[ext]
❻   File.open(LOG_FILE, 'a') do |log|
      log.puts([Time.now, filename].join("\t") + "\n")
    end
  end

  dont_play_file_proc = lambda do |filename| puts "I'm not playing #{filename}. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required