Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simpler way to modify a string

I recently solved this problem, but felt there is a simpler way to do it. I'd like to use fewer lines of code than I am now. I'm new to ruby so if the answer is simple I'd love to add it to my toolbag. Thank you in advance.

goal: accept a word as an arg, and return the word with it's last vowel removed, if no vowels - return the original word

def hipsterfy(word)
    vowels = "aeiou"
    i = word.length - 1
    while i >= 0
        if vowels.include?(word[i])
            return word[0...i] + word[i+1..-1]
        end
        i -= 1
    end
    word
end
like image 480
David Venegas Avatar asked Dec 08 '22 09:12

David Venegas


1 Answers

try this regex magic:

def hipsterfy(word)
  word.gsub(/[aeiou](?=[^aeiou]*$)/, "")
end

how does it work?

[aeiou] looks for a vowel., and ?=[^aeiou]*$ adds the constraint "where there is no vowel match in the following string. So the regex finds the last vowel. Then we just gsub the matched (last vowel) with "".

like image 65
Les Nightingill Avatar answered Dec 23 '22 15:12

Les Nightingill