Tech and travel

Little Ruby script for generating passwords

2007-03-14

Ruby is a scripting language, in the same league as Perl and Python. It is fully object-oriented, and comes batteries includes like Python, which means it comes with a full library installed by default. It is receiving a lot of attention these days due to the Ruby on Rails web application framework, which is indeed a very capable and surprisingly easy to use framework (probably more on this in a later article). Here I’ll show you a small script used to generate a (pseudo-)random password, showing a very small subset of the capabilities of Ruby for scripting.

This is the script :

letters = ""
"a".upto("z") {|s| letters = letters + s}
"A".upto("Z") {|s| letters = letters + s}
"0".upto("9") {|s| letters = letters + s}
password = ""
8.times { password += letters[rand(letters.length), 1] }
print password

First an empty string called letters is created. Then we get a taste of Ruby’s full object orientedness. The string “a” is an object, and it has a method called upto(), which generates all the characters upto the one given as a parameter. This upto() method can take a block, which is a series of instructions that is executed for each character generated. This character is passed as a parameter to the block, using the |s| construct. In the block, the char is then added to the letters string. The same is done for the uppercase letters and digits.

Then an empty password string is generated. We then loop 8 times, using the times() method of the 8 object. Yes indeed, literal numbers have methods as well in Ruby. A block is given to the times method, which will then get executed the specified number of times. In the block, we select a random letter from the letters string, by calling the default rand method, which takes as parameters the upper bound of the random interval. This is set to the length of the letters string here. We then select a character from the letters string by selecting a range of chars starting at the random position and of length 1. Lastly the password is printed.

The script is run as follows, with the output shown as well :

C:\scripts\ruby>ruby random_password.rb
9XhsZa1K

Copyright (c) 2024 Michel Hollands