A Simple Randomizer for Ruby

In migrating out of MovableType I had to leave the [dark miserable depressing] world of PHP behind. So I had to rewrite some scripts in Ruby. One of said scripts is a piece of code that selects an entry from an array and returns it to the body of the code so that you can have an area that updates pretty quickly.

This was one of the first things I learned to do in PHP (thanks to Waldo patience and direction). That code was pretty simple, but not very readable or elegant:

<pre> <?php

// called by
// <?php echo $contents[$random_key][“text”]; ?>
// <?php echo $contents[$random_key][“image”]; ?>

// Gimme a number, any number

srand ((float) microtime() * 10000000);

// Define the array

$contents0[image] = ‘…’;
$contents0[text] = ‘…’;

// Choose your poison

$random_key = array_rand($contents);

?>

Not very elegant. It works, but it’s just nasty. In Ruby it’s pretty straight forward and I figured someone else learning ruby might be able to learn from this:

<pre> #! /usr/bin/env ruby

class RandomImage

PHOTOS = [ # Define the array of photos. Maybe eventually do this with YAML
  1. Image Name Caption
    [ ‘930lights.jpg’, ‘Caption’ ],
    [ ‘arlingtonclouds.jpg’, ‘Caption’ ],
    … # Repeat 24 times
    ]
def show_random_image
  1. Select the array entry
    @photo = PHOTOS[rand(24)]
  1. Give some local variables
    filename = @photo0
    caption = @photo1
  1. Echo statement definitions
    random_image_call = “”media/images/design/masthead/#{filename}\" alt=\“masthead image\” height=\“250\” width=\“725\” border=\“0\” />"
    random_image_caption = “#{caption}”
    end
    end

You have an array defined. To get to an entry in the array you would type @photo[n] to get to the filename or caption you’d add the second level of access @photo[n][0]. Since we want the caption to match the photo, we only want to run rand once. Put that into a variable, and then operate on that variable.

Muy sexy.

Things to do in the future

  1. Make this a Mephisto plugin
  2. Use YAML instead of an inline array
  3. Get rich off the proceeds

Okay, so two out of three wouldn’t be bad.

  1. Linda says:

    very nice!I wonder how many WP depveolers can make it in just a few lines as well lol! I guess not many ;)bookmarking this page, I have a feeling it might come handy sometime!:)

Post a comment

Name or OpenID (required)


(lesstile enabled - surround code blocks with ---)