字母移位加密(凯撒密码)实现求助:Ruby代码编写疑问
Solving Your Caesar Cipher Shift Issue in Ruby
Hey there! You're already on the right track with defining your alphabet array—let's build out that cipher function step by step to get your letter shifting working perfectly.
Core Logic Breakdown
The key steps you need to wrap up this feature are:
- Check if each character is a letter (we don't want to shift spaces, punctuation, or numbers)
- Locate the character's position in your alphabet array
- Calculate its new position by adding 3, with wrap-around logic for when we pass 'z'
- Preserve the original character's case (uppercase stays uppercase, lowercase stays lowercase)
- Reassemble all processed characters back into a single string
Complete Working Code
Here's how to implement this with your existing alphabet setup:
# Define your lowercase alphabet array Alphabet = ('a'..'z').split('') def cypher(input_sentence) # Split the input into individual characters and process each one input_sentence.chars.map do |char| # Check if the character is a letter (case-insensitive) if Alphabet.include?(char.downcase) # Get the original index of the lowercase version of the character original_index = Alphabet.index(char.downcase) # Calculate new index: add 3, then use modulo 26 to wrap around the alphabet new_index = (original_index + 3) % 26 # Get the new character from the alphabet array new_char = Alphabet[new_index] # Match the original character's case char == char.upcase ? new_char.upcase : new_char else # Non-letter characters (spaces, commas, etc.) stay exactly the same char end end.join # Combine the processed characters back into a single string end # Test the function with examples puts cypher("Hello, World!") # Outputs: Khoor, Zruog! puts cypher("ABCxyz") # Outputs: DEFabc
Let's Walk Through the Key Parts
input_sentence.chars.map: Splits your input into an array of characters, then runs each one through the processing logic.Alphabet.index(char.downcase): Finds the position of the lowercase version of your character in the array (e.g., 'H' becomes 'h', which sits at index 7).(original_index + 3) % 26: The modulo operator (%) is critical here—it ensures that when we pass 'z' (index 25), 25 + 3 = 28, and 28 % 26 = 2, which points to 'c' (the correct wrap-around character).- Case preservation: We check if the original character was uppercase with
char == char.upcase, then adjust the new character's case to match the original.
Bonus: Make It Flexible
If you ever want to adjust the shift amount (not just stick to 3), you can turn the shift into a parameter:
def cypher(input_sentence, shift = 3) input_sentence.chars.map do |char| if Alphabet.include?(char.downcase) original_index = Alphabet.index(char.downcase) new_index = (original_index + shift) % 26 new_char = Alphabet[new_index] char == char.upcase ? new_char.upcase : new_char else char end end.join end # Now you can shift by any number! puts cypher("Test", 5) # Outputs: Yjxy
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

