Ruby joy

This is mainly to annoy Emma. She mentioned that she’d had to implement a conversion between base 36 and base something-else (64?). I cannot begin to describe how horrible that would be in COBOL. But in Ruby… ;-)

Admittedly, to do this more “the Ruby way”, I’d write this as a module, or a mixin, or something. But for now, this will do. Call it proof of concept, if you will. I’m very happy with the conversion from a string in base b to an internal integer type, as it uses a beautiful method called “inject”; this is, to a certain extent, very much like the “foldl/foldr” of ML which I learnt in my CompSci course. It’s so elegant! Want to be able to do something similar with the conversion back to string, but I’m pretty sure I can’t.

#!/usr/local/ror/bin/ruby -w
# This works up to base 64. Easily extensible,
# just add more to the $base_ch array.

$base_ch = Array.new [('0'..'9').to_a,
                      ('a'..'z').to_a,
                      '+','/',
                      ('A'..'Z').to_a].flatten

def int_from_base(str,base)
  str.split(//).inject(0) {|v,d| v*base + $base_ch.index(d)}
end

test = int_from_base("7f3ks0g6",36)
puts test

–> 581417181510

def int_to_str_base(num,base)
  result = ""
  while (num > 0) do
    result << $base_ch[num % base]
    num /= base
  end
  result.reverse
end

out = int_to_str_base(test,64)
puts out

–> 8tvay56

2 Comments »

  1. “This is mainly to annoy Emma. ” Hey!!

    On the rest of the post…. get laid dude, get laid! ;-) Nah, it does look cooler than the cobol method that’s for sure!

    Comment by Emma — 28th June, 2006 @ 7:12 am

  2. More functional (and elegant) version of the second method:

    def int_to_str_base(num,base)
      if (num == 0)
        ""
      else
        int_to_str_base(num / base, base) << $base_ch[num % base]
      end
    end
    

    I think this is tail-recursive, but not sure. I don’t really remember what that means!

    Comment by Michael — 9th September, 2006 @ 9:17 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment