Created
January 25, 2014 03:31
-
-
Save threeifbywhiskey/8611423 to your computer and use it in GitHub Desktop.
Adds Perl's XOR-able strings to Ruby, except that an argument longer than the receiver will be cycled as needed and a Fixnum argument frobnicates (see memfrob(3)) the receiver, though not necessarily with 42. Also, non-alphanumeric XOR pairs for gits and shiggles.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module XOR | |
def ^ other | |
case other | |
when Fixnum | |
chars.map { |c| (c.ord ^ other).chr }.join | |
when String | |
chars.zip(other.chars.cycle).map { |a, b| (a.ord ^ b.ord).chr }.join | |
else | |
raise ArgumentError, "must be String or Fixnum" | |
end | |
end | |
def non_alphanumeric_xor_pair | |
syms = '`~!@#$%^&*()_+{}|[]\\\'";:,./<>?' | |
ords = syms.chars.map &:ord | |
pair = ['', ''] | |
chars.map(&:ord).each do |o| | |
candidates = [] | |
ords.each do |a| | |
ords.each do |b| | |
candidates << [a, b] if a ^ b == o | |
end | |
end | |
return [] if candidates.empty? | |
winner = candidates.sample | |
pair[0] << winner.pop | |
pair[1] << winner.pop | |
end | |
pair | |
end | |
end | |
class String | |
include XOR | |
end | |
if $0 == __FILE__ | |
eval DATA.read, nil, $0, __LINE__ + 4 | |
end | |
__END__ | |
require 'test/unit' | |
class TestXOR < Test::Unit::TestCase | |
def test_with_fixnum | |
assert_equal 'abc' ^ 5, 'dgf' | |
end | |
def test_with_string | |
assert_equal 'Just another Ruby hacker', | |
'*+.]@:./[@;)].*<]](_<+>^' ^ '`^])`[@@/(^[}|_^$}@>_@[,' | |
end | |
def test_with_cycled_string | |
assert_equal 'RubyRuby' ^ '<3', 'nF^JnF^J' | |
end | |
def test_with_invalid_argument | |
assert_raise(ArgumentError) { 'abc' ^ [] } | |
end | |
def test_xor_pair | |
a, b = 'Ruby'.non_alphanumeric_xor_pair | |
assert_equal a ^ b, 'Ruby' | |
end | |
def test_unpairable_string | |
assert_empty '<3'.non_alphanumeric_xor_pair | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment