Advertisement
Guest User

Untitled

a guest
Jul 20th, 2019
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.02 KB | None | 0 0
  1. def encrypt(string, shift)
  2.   string.map! do |char|
  3.     if char.ord == 32
  4.       char
  5.     elsif (char.ord + shift) < 123
  6.       (char.ord + shift).chr
  7.     else
  8.       (char.ord + shift - 26).chr
  9.     end
  10.   end
  11.   string.join
  12. end
  13.  
  14. def decrypt(string, shift)
  15.   string.map! do |char|
  16.     if char.ord == 32
  17.       char
  18.     elsif (char.ord - shift) > 96
  19.       (char.ord - shift).chr
  20.     else
  21.       (char.ord - shift + 26).chr
  22.     end
  23.   end
  24.   string.join
  25. end
  26.  
  27. puts "Enter filename to encrypt and shift: "
  28. filename = gets.chomp
  29. shift = gets.to_i
  30.  
  31. encrypted = ""
  32. File.open(filename, "r") do |f|
  33.   f.each_line do |line|
  34.     encrypted += encrypt(line.chomp.chars, shift) + "\n"
  35.   end
  36. end
  37. puts encrypted
  38.  
  39. File.open(filename, "w") do |line|
  40.   line.puts "\r" + encrypted
  41. end
  42.  
  43. puts "Enter filename to decrypt and shift: "
  44. filename = gets.chomp
  45. shift = gets.to_i
  46.  
  47. decrypted = ""
  48. File.open(filename, "r") do |f|
  49.   f.each_line do |line|
  50.     decrypted += decrypt(line.chomp.chars, shift) + "\n"
  51.   end
  52. end
  53. puts decrypted
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement