0

I'm trying to iterate through the vowels "aeiou" and move every letter forward, returning the string "eioua". This is my code:

def vowel(letter)
  vowels = "aeiou"
  string = ""
  index = 0
  while index < letter.length
    current_id = vowels.index(letter)
    next_vowel = vowels[current_id + 1]
    string += next_vowel
    index += 1
  end
  string
end

When I pass "aeiou" as a parameter to my method, it just takes "a", and prints "eeeee".

vowel("aeiou") # => "eeeee"
1
  • What is your question? Commented Apr 3, 2016 at 7:12

2 Answers 2

2

You are always appending the vowel, found by index current_id = vowels.index(letter) (increased by one.) That’s why the code appends e (the next to a) five times. index variable is used as a loop counter only.

There is another glitch with this code: when letter is the last one, current_id is an index of the last letter and vowels[current_id + 1] is nil.

At the moment I am unable to provide a solution for this problem, because the description and expected result are not consistent: “moving every letter forward” won’t produce "eioua" on the given input.

Sign up to request clarification or add additional context in comments.

2 Comments

Ah, sorry I didn't mean one letter forward- I meant that each vowel would become the next vowel to the right of it so "a" would become "e" and "u" would become "a." I also noticed that vowels[current_id + 1] becomes nil but I still don't fully understand why can you elaborate? Thank you for the helpful feedback!
When current_id is an index of the last letter, current_id + 1 is an index that is greater than string length, that said, it’s an non-existing index. 'abc'[3] is e.g. nil.
1

If you want to rotate the letters of the word (and form a new word, as opposed to modifying the word in place) one way is:

str = "aeiou"

new_str = str.chars.rotate.join.   #=> "eioua" 
str                                #=> "aeiou" 

If you wish to modify the string in place:

str.object_id.                     #=> 70128532752540 
str.replace(str.chars.rotate.join) #=> "eioua"
str                                #=> "eioua" 
str.object_id                      #=> 70128532752540 

1 Comment

This is a much better way of doing it. Ruby has all these short Enumerator based methods that are really great when they can be used in conjunction.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.