用于删除字符串中元音的Ruby代码

时间:2016-01-22 22:33:23

标签: ruby string

我正在尝试用Ruby编写代码,从字符串中删除所有元音:

def remvowel(string)
  i = 0
  dv_string = []
  while i < string.length
    if (string[i] != "a" || string[i] != "e" || string[i] != "i" || string[i] != "o" || string[i] != "u")
      dv_string.push(i)
      i += 1
    end
    i += 1
  end
  return dv_string.join
end

但它不是正确的。当我运行remvowel("duck")时,它会返回"02",就像"dc"的索引位置一样。我错过了什么,但我不知道是什么。

5 个答案:

答案 0 :(得分:15)

你可以:

string.gsub(/[aeiou]/, '')

甚至更好:

string.tr('aeiou', '')

删除字符串中字符的最佳工具是......

string.delete('aeiou')

答案 1 :(得分:4)

那是因为你推了i而不是string[i]

dv_string.push(i)

这就是你想要的:

dv_string.push(string[i])

然而,这是完成任务的相当冗长和迂回的方式。一个更惯用的Ruby方法看起来就像发布的任何一个:

def remvowel(string)
  string.gsub /[aeiou]/, ''
end

def remvowel(string)
  string.tr 'aeiou',''
end

def remvowel(string)
  string.delete 'aeiou'
end

答案 2 :(得分:2)

你几乎是对的:

def remvowel(string)
    i = 0
    dv_string = []

    while i < string.length
        if (string[i] != "a" || string[i] != "e" || string[i] != "i" || string[i] != "o" || string[i] != "u")
            # Push the letter, not i
            dv_string.push(string[i])
            # Don't increment i here
        end

        i += 1
    end

    return dv_string.join
end

如果遇到辅音,你的算法会增加两次,所以你跳过每一个字母。

答案 3 :(得分:1)

以下是另一种方法:

s = "Hello, how are you you?"
vowels = "aeiou"
puts (s.chars - vowels.chars).join
#=> Hll, hw r y y?

答案 4 :(得分:0)

感谢大家的贡献。感谢大家(特别是你,Cary Swoveland),我不仅知道将来更好的方法,但我甚至找到了一个回答我的“风景路线”的方式!

def remvowel(string)
    i = 0
    dv_string = []

    while i < string.length
        dv_string.push(string[i])

        if (string[i] == "a" || string[i] == "e" || string[i] == "i" || string[i] == "o" || string[i] == "u")
            dv_string.delete(string[i])
        end

        i += 1
    end

    return dv_string.join
end

当然,从现在开始,我将从这些回复中做出更明智的方式,但任务完成了!