From: Daniel Berger Date: 2002-12-10T06:10:47+09:00 Subject: Re: Ruby base64 encoding/decoding Emiel van de Laar wrote: > * Michael Neumann (520079130762-0001@t-online.de) wrote: > > On Mon, 2002-12-09 at 21:22, Emiel van de Laar wrote: > > > Fellow Ruby users, > > > > > > I'm looking for a Ruby module that handles base64 encoding/decoding. RAA > > > doesn't seem to carry one. Perhaps it doesn't exist and someone with > > > some spare time could port the PERL version. :) In my opinion this is > > > a fundamental module the Ruby community is missing at the moment. > > > > See String#unpack and Array#pack. > > > > s = [binaryString].pack("m") # encodes binaryString as base64 > > s.unpack("m") # decodes s > > Wow it comes standard with Ruby. Nice. Thanks for pointing me in the > right direction. ;) > > Emiel > -- > E F van de Laar > Beheers Commissaris dispuut Interlink > +31648183479 > www.il.fontys.nl/~emiel There is a base64 module, btw, that comes as part of the standard distro, so you can do: require "base64". 4 methods available: decode decode64 encode encode64 The full code is below. These methods should be wrapped in their own module, IMHO, to avoid name collision. Regards, Dan # base64.rb from 1.6.7 require "kconv" def decode64(str) str.unpack("m")[0] end def decode_b(str) str.gsub!(/=\?ISO-2022-JP\?B\?([!->@-~]+)\?=/i) { decode64($1) } str = Kconv::toeuc(str) str.gsub!(/=\?SHIFT_JIS\?B\?([!->@-~]+)\?=/i) { decode64($1) } str = Kconv::toeuc(str) str.gsub!(/\n/, ' ') str.gsub!(/\0/, '') str end def encode64(bin) [bin].pack("m") end def b64encode(bin, len = 60) encode64(bin).scan(/.{1,#{len}}/o) do print $&, "\n" end end