Ruby Succinctness competition

For some reason I never was that excited about trying to accomplish these sorts of things in Perl:

1..rand(256)).inject("") {|string,n| string + ('a'..'z').to_a[rand(25)] }

This generates a string from 1 to 256 characters long, containing random letters from 'a' to 'z'.  

Normally, I wouldn't use something that's quite so unreadable, but I'm starting to like Ruby's way of taking what should be a very simple operation that I might have done in 3-5 lines in Perl and boiling it down to a single line.

I'd love to see if anyone can make this more succinct (but one line is still a requirement!)

Here's the code in it's context. It's just a test script writing into my partition table every minute so I can verify my Events from previous posts are working correctly.

#!/usr/bin/ruby

require 'mysql'


dbh = Mysql.new( "server.domain.com",
    "user", "pass", "test", 3306)

loop do
    string = ""; rand(256).times { string << ('a'..'z').to_a[rand(25)] }
    dbh.query( "INSERT INTO log (logged, text) VALUES (
'#{Time.now.strftime( '%Y-%m-%d %H:%M:%S')}', 
'#{(1..rand(256)).inject("") {|string,n| string + ('a'..'z').to_a[rand(25)] }}'
)" );
    sleep 60
end

Trackback URL for this post:

http://mysqlguy.net/trackback/10
Event Scheduling reliability →← Using Events to manage Table Partitioning by Date: wrap-up

6 Comments

in python:import
Submitted by DaveE (not verified) on February 14, 2008 - 10:37am.

in python:

import random,string
string="".join([random.choice(string.lowercase) for i in range(0,int(random.uniform(1,256)))])

does importing libraries count towards a one liner  i guess they should... but python doesnt have a rand function in the global ns.

A shorter line: +1 For using
Submitted by jay on February 14, 2008 - 11:07am.
A shorter line: +1
For using Python and not Ruby: -2 ;)

Not realizing it wasn't Ruby until I started typing it in: -10 (for me)

I'd suggest this in perl:
Submitted by rhesa (not verified) on February 14, 2008 - 1:04pm.

I'd suggest this in perl:

$rnd = join "", map { (a..z)[rand 26] } 1..rand 256;

Neither unreadable nor long-winded :-)

I was going to submit
Submitted by Xaprb (not verified) on February 16, 2008 - 4:35pm.

I was going to submit something very similar to rhesa.  It's not so much a language thing, it's a way of thinking.  Ruby encourages that.  Perl allows it.  Java doesn't :-)  Regardless of the language, functional programming rocks for things like this.

Ruby:(1..rand(256)).map{(97+r
Submitted by TPReal (not verified) on July 17, 2008 - 11:15am.

Ruby:
(1..rand(256)).map{(97+rand(26)).chr}.join

Exactly what I was looking
Submitted by jay on July 20, 2008 - 6:18pm.

Exactly what I was looking for, thanks!  I'm still at the point with my Ruby that I need to keep rereading the function lists in the core/standard library to find functions like map and make sure I know what they do....