module Nuggets::String::XorMixin

Public Instance Methods

^(other, require_same_length = false)
Alias for: xor
str ^ other → new_string click to toggle source
xor(other) → new_string

Bitwise EXCLUSIVE OR.

   # File lib/nuggets/string/xor_mixin.rb
38 def xor(other, require_same_length = false)
39   format = 'B*'
40   binary = [self, other.to_s].map { |s| s.unpack(format).first }
41 
42   length = binary.map { |s| s.length }.inject { |a, b|
43     if require_same_length
44       a == b ? a : raise(::ArgumentError, 'must be of same length')
45     else
46       [a, b].max
47     end
48   }
49 
50   [binary.map { |s| s.to_i(2) }.
51           inject { |a, b| a ^ b }.
52           to_binary_s(length)].pack(format)
53 end
Also aliased as: ^