修改字符串的更简单方法

simpler way to modify a string

我最近解决了这个问题,但觉得有更简单的方法。我想使用比现在更少的代码行。我是 ruby 的新手,所以如果答案很简单,我很乐意将其添加到我的工具包中。提前谢谢你。

目标: 接受一个单词作为参数,return 删除最后一个元音的单词,如果没有元音 - return 原始单词

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

这是另一种方法。

  1. 反转字符串的字符

  2. 使用find_index得到这个反转字符串第一个元音位置

  3. 删除该索引处的字符

  4. 取消反转字符并将它们重新组合在一起。

    reverse_chars = str.chars.reverse
    vowel_idx = reverse_chars.find_index { |char| char =~ /[aeiou]/ }
    reverse_chars.delete_at(vowel_idx) if vowel_idx
    result = reverse_chars.reverse.join
    

试试这个正则表达式魔术:

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

它是如何工作的?

[aeiou] 寻找一个元音字母。,?=[^aeiou]*$ 添加约束条件“在后面的字符串中没有元音字母匹配。所以正则表达式找到最后一个元音字母。然后我们只是 gsub匹配(最后一个元音)与“”。

您可以使用rindex to find the last vowel's index and []=删除对应的字符:

def hipsterfy(word)
  idx = word.rindex(/[aoiou]/)
  word[idx] = '' if idx
  word
end

需要 if idx 因为 rindex returns nil 如果没有找到元音。请注意 []= 修改 word.

还有rpartition which splits the string at the given pattern, returning an array containing the part before, the match and the part after. By concat-enating前者和后者,可以有效去掉中间部分:(即元音)

def hipsterfy(word)
  before, _, after = word.rpartition(/[aoiou]/)
  before.concat(after)
end

这个变体 returns 一个 新的 字符串,word 不变。

另一种处理 last 事件的常用方法是 reverse the string so you can deal with a first occurrence instead (which is usually simpler). Here, you can utilize sub:

def hipsterfy(word)
  word.reverse.sub(/[aeiou]/, '').reverse
end