Article 14R7N CodeSOD: Random Ruby

CodeSOD: Random Ruby

by
Jane Bailey
from The Daily WTF on (#14R7N)

256px-Corindons_rose_et_pourpre_%2820_mm

Peri, the new intern, was proving her worth as a programmer rapidly. She was great with finding clever solutions to problems, and she didn't bother the more senior devs too often while doing it: a boon, as they were trying to get their own work done.

So when Steven assigned her a simple task-generate some unique IDs for repeated dynamic elements so the automated test team could keep track of which ones were which-he figured she didn't need any hand-holding.

"Good news!" she reported a few days later. "I completed that task you assigned me easily, ahead of schedule, and in only a single line of code." She preened, clearly proud of her work.

Steven, who had long since moved on to other things, smiled at her. "That's great, Peri! I'll get you another ticket in a few minutes, after I approve your pull request."

Peri skipped away happily.

Steven finished the line he was on, pulled up Stash to skim over the PR-and stopped short.

You see, the thing about Ruby is that you can do a lot in a single line of code. It's very compact and expressive that way. So when Peri said she'd written only a single line, well ...

unique_id = ('a'..'z').to_a.shuffle[0,8].join

For those of you who aren't familiar with Ruby, let's break that down:

  • ('a'..'z') creates a Range object for iterating over the characters 'a' through 'z'
  • to_a casts to an array by iterating over the Range and pushing each element into a fresh array
  • shuffle randomizes the elements in the array (which internally calls Ruby's rand function 25 times)
  • [0,8] grabs the first eight elements in the array and creates a new array with them
  • join merges that array into a string

Steven declined the pull request, replacing it with his own, far less "clever" code:

rand(1000000000)
TheDailyWtf?d=yIl2AUoC8zA9SuDOEW79d8
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments