Skip to content

Instantly share code, notes, and snippets.

@skalibog
Created August 8, 2019 14:44
Show Gist options
  • Save skalibog/7e9acd8f2adeb8745ae96d24108f0410 to your computer and use it in GitHub Desktop.
Save skalibog/7e9acd8f2adeb8745ae96d24108f0410 to your computer and use it in GitHub Desktop.
# ruby 2.6.3
#
class Crypto
def initialize(method, string, count)
@method = method
@string = string
@count = count
end
def call
return @string if @string.nil? || @string.empty? || @count <= 0
case @method
when 'encrypt'
p encrypt
when 'decrypt'
p decrypt
else
raise ArgumentError.new("Method must be in %w[encrypt decrypt]")
end
end
private
def encrypt
result = @string
@count.times do |_|
odd = ''
even = ''
result.split('').each_with_index do |letter, index|
index.even? ? odd << letter : even << letter
end
result = odd + even
end
result
end
def decrypt
length = @string.length.even? ? @string.length / 2 : @string.length / 2 + 1
result = @string
@count.times do |_|
odd = result[0...length]
even = result[length..]
result = ''
length.times do |index|
result << odd[index] << even[index]
end
end
result
end
end
Crypto.new("encrypt", "abcdefghij", 1).call
Crypto.new("decrypt", "acegibdfhj", 1).call
Crypto.new("encrypt", "abcdefghij", 2).call
Crypto.new("decrypt", "aeidhcgbfj", 2).call
Crypto.new("encrypt", "abcdefghij", 3).call
Crypto.new("decrypt", "aihgfedcbj", 3).call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment