From: Robert Klemme Date: 2007-01-29T07:30:09+09:00 Subject: Re: "a string".xor("another string") On 28.01.2007 21:28, Erik Veenstra wrote: > I want to do an XOR of two strings: > > "a string".xor("another string") > > It's not that hard to implement, but it's not fast either, > since it walks through the data string, byte-by-byte. > > Any ideas? For example: "It's memory-hungry!". Any solutions? > > gegroet, > Erik V. - http://www.erikveen.dds.nl/ > > ---------------------------------------------------------------- > > class String > def xor(other) > if other.empty? > self > else > a1 = self.unpack("c*") > a2 = other.unpack("c*") > > a2 *= 2 while a2.length < a1.length > > a1.zip(a2).collect{|c1,c2| c1^c2}.pack("c*") > end > end > end > > ---------------------------------------------------------------- irb(main):008:0> a="a string" => "a string" irb(main):009:0> b="another string" => "another string" irb(main):014:0> s="";[a.size, b.size].max.times {|i| s << ((a[i]||0) ^ (b[i]||0))} => 14 irb(main):015:0> s => "\000N\034\000\032\f\034Gstring" Hm.... robert