05th Oct 2006
N yvggyr Ehol…
I’ve been asked to lead a Ruby session at my school for a small group of students interested in learning the language. As such, I’ve been brushing up on it lately, and I came up with a fun little script I thought I’d share.
Our topic is cryptography, and in the spirit of fun I thought I would show how easy it is to write a ROT13 cipher in Ruby. Here it is:
def uppercase_swap(byte) if /[A-M]/ === byte.chr then byte += 13 else byte -= 13 end end def lowercase_swap(byte) if /[a-m]/ === byte.chr then byte += 13 else byte -= 13 end end ARGV.shift.each_byte do |byte| byte = uppercase_swap byte if /[A-Z]/ =~ byte.chr byte = lowercase_swap byte if /[a-z]/ =~ byte.chr print byte.chr.to_s end print "\n"
As you can see, it’s not very big. Ignoring the 2 function definitions at the top momentarily, all we are doing is taking the first argument (ARGV.shift), and iterating through each byte –each character of the string. With each byte, we are checking to see if it is an upper or lowercase letter and calling the appropriate function to swap it with a different letter if it is.
Simple. Nice.
If anyone has any input on how to improve this code, please let me know. UPDATE: I made it better, here’s how:
def swapLetter(byte) if /[A-M]|[a-m]/ === byte.chr then byte += 13 else byte -= 13 end end ARGV.shift.each_byte do |byte| byte = swapLetter(byte) if /[A-Z]|[a-z]/ =~ byte.chr print byte.chr.to_s end print "\n"
Merging functions is goood.
[…] Patr1ck has posted instructions on performing ROT13 in Ruby. Colin has responded with the Perl version. Here’s the Python version. import codecs rot13ed_data = codecs.getencoder(’rot13′)(data_to_rot13)[0] […]
Try this for short:
ruby -n -e ‘puts $_.tr(”a-mn-zA-MN-Z”, “n-za-mN-ZA-M”)’
Just pipe/redirect your input into that.