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
in python:import
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
I'd suggest this in perl:
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
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
Ruby:
(1..rand(256)).map{(97+rand(26)).chr}.join
Exactly what I was looking
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....
Post new comment