From: Robert Klemme Date: 2012-08-03T01:29:25+09:00 Subject: Re: working with large binary strings? On Wed, Aug 1, 2012 at 1:55 PM, bob hope wrote: > Hi, so in the spirit of not cluttering the forum I will ask my somewhat > unrelated but still related question here. So I have finished > implementing this, but have run into one issue, when I XOR strings > together like this: > > def xor_strings(string_array) > > processed_strings = [] > > string_array.each do |string| > processed_strings << NArray.to_na(string, "byte") > end > > processed_strings.inject(:^).to_s > end > > the result is not always the same size as the set of strings. I believe > some optimization is being done for me and I need to avoid it, however > googling for Narray and XOR has not led me to any success. I swear this > is my last question regarding this, as after I have this fixed I am all > the way done :D I am really not sure what you're after, but maybe this does help: irb(main):013:0> x = SecureRandom.random_bytes(10) => "\r\xC8\xA9\x99\t\f\x12\xC9#]" irb(main):014:0> y = SecureRandom.random_bytes(10) => "\x12\x86p?\x19q2\xA6\e\x88" irb(main):015:0> z = "".force_encoding 'BINARY' => "" irb(main):016:0> x.each_byte.zip(y.each_byte) {|a,b| z<<(a^b)} => nil irb(main):017:0> z.length => 10 irb(main):018:0> z => "\x1FN\xD9\xA6\x10} o8\xD5" Or, for multiple strings irb(main):020:0> z = "".force_encoding 'BINARY' => "" irb(main):024:0> max = arr.map(&:bytesize).max => 10 irb(main):025:0> max.times {|i| z[i] = arr.inject(0) {|agg, bytes| b = bytes[i]; b ? agg ^ b.ord : agg}.chr} => 10 irb(main):026:0> z => "\x1FN\xD9\xA6\x10} o8\xD5" Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/