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, line 38
def xor(other, require_same_length = false)
  format = 'B*'
  binary = [self, other.to_s].map { |s| s.unpack(format).first }

  length = binary.map { |s| s.length }.inject { |a, b|
    if require_same_length
      a == b ? a : raise(::ArgumentError, 'must be of same length')
    else
      [a, b].max
    end
  }

  [binary.map { |s| s.to_i(2) }.
          inject { |a, b| a ^ b }.
          to_binary_s(length)].pack(format)
end
Also aliased as: ^