Module: Nuggets::String::XorMixin
- Included in:
- String
- Defined in:
- lib/nuggets/string/xor_mixin.rb
Instance Method Summary collapse
-
#xor(other, require_same_length = false) ⇒ Object
(also: #^)
call-seq: str ^ other => new_string str.xor(other) => new_string.
Instance Method Details
#xor(other, require_same_length = false) ⇒ Object Also known as: ^
call-seq:
str ^ other => new_string
str.xor(other) => new_string
Bitwise EXCLUSIVE OR.
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# 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 |