Skip to content

Instantly share code, notes, and snippets.

@rickywid
Created May 14, 2015 15:04
Show Gist options
  • Save rickywid/603b548be6214728b6ec to your computer and use it in GitHub Desktop.
Save rickywid/603b548be6214728b6ec to your computer and use it in GitHub Desktop.
#OBJECTIVE
#Implement a caesar cipher that takes in a string and the shift factor and then outputs the modified string
puts "enter a sentence"
input = gets.chomp #store string in variable 'input'
puts "enter offset number"
offset = gets.chomp.to_i #store number in variable 'offset'. Convert string to integer (gets.chomp by default returns a string value)
def caesar_cipher (x,num) #define method
alpha = [] #create an empty array to store alphabet
('a'..'z').each do |x| #iterate through a-z
alpha << x #store each letter in 'alpha' array
end
string = x.split("") #converts string to array. eg. ["h","e","l","l","o"]
string.each do |y| #iterate through each letter in the string array
alpha.each do |x| #iterate through each letter in the alphabet (alpha)
if y == x #compare and find any matching letters
index = alpha.index(x) #find the index position of the matching letter in the "alpha" array
index += num #offset index position based on "num" parameter
print alpha[index] #print letter
end
end
end
puts ""
end
caesar_cipher(input,offset)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment