【问题标题】:Searching for vowels in Ruby在 Ruby 中搜索元音
【发布时间】:2020-08-13 01:15:38
【问题描述】:
str = "Find the vowels in this string or else I'll date your sister"

我正在计算一个字符串中元音的数量,我相信我已经做到了,但我通过将每个字母附加到一个数组并获取数组的长度来做到这一点。有什么更常见的方法来做到这一点。也许用 +=?

str.chars.to_a.each do |i|
    if i =~ /[aeiou]/ 
        x.push(i)
    end
end
x.length

【问题讨论】:

    标签: ruby


    【解决方案1】:

    但这里有更好的答案 =)。原来我们有一个String#count方法:

    str.downcase.count 'aeiou'
    #=> 17
    

    【讨论】:

    • 我喜欢你的.. 因为这个问题不用字符串转换成数组就解决了。
    【解决方案2】:

    如果你想计算元音,为什么不使用count

    str.chars.count {|c| c =~ /[aeiou]/i }
    

    【讨论】:

    • 在 SO 上经常发生最好的答案不是公认的答案,这就是其中一种情况。
    • 只是一个解释:在我写下评论后,提问者改变了主意并接受了这个答案。关键是在您要数数时使用#count。我发现#count 也定义在String 上,后来又添加了一个答案。
    【解决方案3】:

    使用scan

    "Find the vowels in this string or else I'll date your sister".scan(/[aeiou]/i).length
    

    【讨论】:

      【解决方案4】:

      不需要:

      str.chars.to_a
      

      其实str.chars已经是一个数组了

      > String.new.chars.class
       => Array 
      

      稍微重构

      str.chars.each{|i| i =~ /[aeiou]/ ? x : nil}
      x.length
      

      但最好的解决方案可能是:

      a.chars.map{|x| x if x.match(/[aeiouAEIOU]/)}.join.size
      

      你应该检查 map 块,因为你可以在里面执行一些有用的东西,作为 count 块的替代。

      毫无疑问,使用块计算字符串内元音的最佳解决方案:

      str.chars.count {|c| c =~ /[aeiou]/i }
      

      【讨论】:

        【解决方案5】:

        有更短的化身。

        $ irb
        >> "Find the vowels in this string or else I'll date your sister".gsub(/[^aeiou]/i, '').length
        => 17
        

        【讨论】:

        • 您可以添加.length 来获取元音的数量,因为这就是问题所要求的。
        • 哎呀,错过了。我们开始吧。
        【解决方案6】:

        这是使用String#tr的一种方式:

        str = "Find the vowels in this string or else I'll date your sister"
        
        str.size - str.tr('aeiouAEIOU','').size #=> 17
        

        str.size - str.downcase.tr('aeiou','').size #=> 17
        

        【讨论】:

          猜你喜欢
          • 2010-11-05
          • 1970-01-01
          • 1970-01-01
          • 2012-02-17
          • 2019-07-01
          • 1970-01-01
          • 2017-01-12
          • 2010-11-25
          • 1970-01-01
          相关资源
          最近更新 更多