2

How can I define the -last vowel- in a string?

For example, I have a word "classic"

I want to find that the last vowel of the word "classsic" is the letter "i", and delete that last vowel.

I'm thinking :

def vowel(str)
  result = ""
  new = str.split(" ")
  i = new.length - 1
  while i < new.length
    if new[i] == "aeiou"
      new[i].gsub(/aeiou/," ")
    elsif new[i] != "aeiou"
      i = -= 1
    end
  end
  return result
end
Dil Azat
  • 113
  • 1
  • 1
  • 9
  • 2
    Reverse the string, remove the first vowel, then reverse the string back. – Aetherus Sep 22 '16 at 01:01
  • You might want to edit your first sentence to remove the reference to Java. – pjs Sep 22 '16 at 01:35
  • 1
    Another way is `str = "fabulous"; str[str.rindex(/[aeiou]/)] = '' => ""; str #=> "fabulos"`, or `str.dup.tap { |s| s[s.rindex(/[aeiou]/)] = '' }` if `str` is not to be mutated. – Cary Swoveland Sep 22 '16 at 18:42

3 Answers3

13
r = /
    .*      # match zero or more of any character, greedily
    \K      # discard everything matched so far
    [aeiou] # match a vowel
    /x      # free-spacing regex definition mode

"wheelie".sub(r,'') #=> "wheeli"
"though".sub(r,'')  #=> "thogh"
"why".sub(r,'')     #=> "why" 
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
4

Like @aetherus pointed out: reverse the string, remove the first vowel then reverse it back:

str = "classic"
=> "classic"
str.reverse.sub(/[aeiou]/, "").reverse
=> "classc"
potibas
  • 619
  • 5
  • 7
1
regex = /[aeiou](?=[^aeiou]*\z)/
  • [aeiou] matches one vowel

  • [^aeiou]* matches non-vowel characters 0 or more times

  • \z matches to the end of the string

  • (?=...) is positive forward looking and not including the match in the final result.

Here are a few examples:

"classic".sub(regex, '') #=> "classc"
  "hello".sub(regex, '') #=> "hell"
  "crypt".sub(regex, '') #=> "crypt
davidhu
  • 9,523
  • 6
  • 32
  • 53