ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Ruby] exercise _ Vowel Cipher
    coding for food 2022. 8. 7. 09:57

    Write a method vowel_cipher that takes in a string and returns a new string where every vowel becomes the next vowel in the alphabet.

    # my code
    
    def vowel_cipher(string)
      vowel = "aeiou"
      new_str = ""
      string.each_char do |char|
      	if vowel.include?(char)
          new_idx = vowel.index(char) + 1
          new_str += vowel[new_idx % 5]
        else
          new_str += char
        end
        
      end
      
      return new_str
    
    end
    
    puts vowel_cipher("bootcamp") #=> buutcemp
    puts vowel_cipher("paper cup") #=> pepir cap
    # solution
    
    def vowel_cipher(string)
      vowels = "aeiou"
    
      new_chars = string.split("").map do |char|
        if vowels.include?(char)
          old_idx = vowels.index(char)
          new_idx = old_idx + 1
          vowels[new_idx % vowels.length]
        else
          char
        end
      end
    
      return new_chars.join("")
    end
    
    puts vowel_cipher("bootcamp") #=> buutcemp
    puts vowel_cipher("paper cup") #=> pepir cap
Designed by Tistory.