How do I remove the last vowel in a string in Ruby?

邮差的信 提交于 2019-12-11 02:13:06

问题


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

回答1:


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" 



回答2:


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

str = "classic"
=> "classic"
str.reverse.sub(/[aeiou]/, "").reverse
=> "classc"



回答3:


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


来源:https://stackoverflow.com/questions/39628583/how-do-i-remove-the-last-vowel-in-a-string-in-ruby

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!