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- Image Name Caption
[ ‘930lights.jpg’, ‘Caption’ ],
[ ‘arlingtonclouds.jpg’, ‘Caption’ ],
… # Repeat 24 times
]
- Select the array entry
@photo = PHOTOS[rand(24)]
- 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
- Make this a Mephisto plugin
- Use YAML instead of an inline array
Get rich off the proceeds
Okay, so two out of three wouldn’t be bad.
