# Last index solutions (each_char.with_index vs. while loop)

Here is the code I wrote for the last index problem (using each_char.with index)

def last_index(str, char)
indices = []
str.each_char.with_index do |letter, idx|
if char == letter
indices << idx
end
end
return index[-1]
end

Instructor solution using while loop.
def last_index(str, char)
i = str.length - 1
while i >= 0
if str[i] == char
return i
end
i -= 1
end
end

I understand that his solution would find the last index “faster” but am still wondering if my method would still be acceptable code in this situation. Thanks for your thoughts/feedback.

This part of your code is the only problem. Your array is called indices instead of index.
Otherwise, your code solves the problem and is therefore good in my eyes.

I also used a different way to solve the problem. I don’t think the idea was for you to necessarily come up with exactly what the instructors did.

2 Likes

I also used a different approach to solve it, as follows, but also I went over instructor’s code and understood the steps and it’s the shortest and best way I think.

def last_index(str, char)
i = 0
k = 0
while i < str.length
if str[i] == char
k = i
end
i+=1
end
return k
end