Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- describe "Caesar" do
- latin_encrypter = Caesar.new 4
- dna_encrypter = Caesar.new 3, 'ACTG'
- it 'encrypts correctly' do
- expect(latin_encrypter.encrypt 'hello').to eq "lipps"
- end
- it 'encrypts correctly using DNA alphabet' do
- expect(dna_encrypter.encrypt 'ACCTGA').to eq "GAACTG"
- end
- it 'decrypts correctly' do
- expect(latin_encrypter.decrypt 'lipps').to eq 'hello'
- end
- it 'decrypts correctly using DNA alphabet' do
- expect(dna_encrypter.decrypt 'GAACTG').to eq 'ACCTGA'
- end
- end
- class Caesar
- def initialize(shift, alphabet = 'abcdefghijklmnopqrstuvwxyz')
- @shift = shift % alphabet.size
- @alphabet = alphabet
- end
- def encrypt(string)
- string.chars.map { |char| @alphabet[@alphabet.index(char) + @shift - @alphabet.size] }.join
- end
- def decrypt(string)
- string.chars.map { |char| @alphabet[@alphabet.index(char) - @shift] }.join
- end
- end
- class Caesar
- def initialize(shift, alphabet = ('a'..'z').to_a.join)
- i = shift % alphabet.size #I like this
- @decrypt = alphabet
- @encrypt = alphabet[i..-1] + alphabet[0...i]
- end
- def encrypt(string)
- string.tr(@decrypt, @encrypt)
- end
- def decrypt(string)
- string.tr(@encrypt, @decrypt)
- end
- end
- class Caesar
- def initialize(shift, alphabet = ('a'..'z').to_a.join)
- @shift = shift
- @alphabet = alphabet
- @indexes = alphabet.chars.map.with_index.to_h
- end
- def encrypt(string)
- string.chars.map { |c| @alphabet[(@indexes[c] + @shift) % @alphabet.size] }.join
- end
- def decrypt(string)
- string.chars.map { |c| @alphabet[(@indexes[c] - @shift) % @alphabet.size] }.join
- end
- end
- class Caesar
- def initialize(shift, alphabet = ('a'..'z').to_a.join)
- chars = alphabet.chars.to_a
- @encrypter = chars.zip(chars.rotate(shift)).to_h
- @decrypter = chars.zip(chars.rotate(-shift)).to_h
- end
- def encrypt(string)
- @encrypter.values_at(*string.chars).join
- end
- def decrypt(string)
- @decrypter.values_at(*string.chars).join
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement