尝试使用 Ruby while 循环查找字符串的元音 [英] Trying to find vowels of a string using Ruby while loops

查看:23
本文介绍了尝试使用 Ruby while 循环查找字符串的元音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

def count_vowels(string)
  vowels = ["a", "e", "i", "o", "u"]
  i = 0
  j = 0
  count = 0

  while i < string.length do
    while j < vowels.length do
      if string[i] == vowels[j]
        count += 1
        break
      end

      j += 1
    end

    i += 1
  end

  puts count 
end

我无法找出哪里出错了.如果这个程序遇到一个辅音,它就会停止.另外,如何使用.each"方法解决同样的问题?

I'm having trouble spotting where this goes wrong. If this program encounters a consonant, it stops. Also, how would the same problem be solved using the ".each" method?

推荐答案

问题是你永远不会将 j 重置为零.

The problem is that you never reset j to zero.

你的外层 while 循环第一次运行,也就是将 string 的第一个字符与每个元音进行比较,j 从0(对于a")到 4(对于u").然而,外循环第二次运行时,j 已经是 4,这意味着它随后会增加到 5、6、7 等等.vowels[5]vowels[6] 等都计算为 nil,所以第一个后面的字符永远不会被算作元音.

The first time your outer while loop runs, which is to compare the first character of string to each vowel, j is incremented from 0 (for "a") to 4 (for "u"). The second time the outer loop runs, however, j is already 4, which means it then gets incremented to 5, 6, 7 and on and on. vowels[5], vowels[6], etc. all evaluate to nil, so characters after the first are never counted as vowels.

如果您将 j = 0 行移动到外部 while 循环内,则您的方法可以正常工作.

If you move the j = 0 line inside the outer while loop, your method works correctly.

关于 .each 的第二个问题表明您已经按照正确的思路思考了.while 在 Ruby 中很少见,.each 肯定会有所改进.事实证明,您不能在 String 上调用 .each(因为 String 类不包括 Enumerable),所以你必须先用 String#chars 方法.这样,您的代码将如下所示:

Your second question, about .each, shows that you're already thinking along the right lines. while is rarely seen in Ruby and .each would definitely be an improvement. As it turns out, you can't call .each on a String (because the String class doesn't include Enumerable), so you have to turn it into an Array of characters first with the String#chars method. With that, your code would look like this:

def count_vowels(string)
  chars = string.chars
  vowels = ["a", "e", "i", "o", "u"]
  count = 0

  chars.each do |char|
    vowels.each do |vowel|
      if char == vowel
        count += 1
        break
      end
    end
  end

  puts count
end

不过,在 Ruby 中,我们有更好的方法来做这种事情.一个特别适合这里的是 Array#count.它接受一个块并为数组中的每个项目评估它,然后返回块返回 true 的项目数.使用它我们可以写一个这样的方法:

In Ruby, though, we have much better ways to do this sort of thing. One that fits particularly well here is Array#count. It takes a block and evaluates it for each item in the array, then returns the number of items for which the block returned true. Using it we could write a method like this:

def count_vowels(string)
  chars = string.chars
  vowels = ["a", "e", "i", "o", "u"]

  count = chars.count do |char|
    is_vowel = false
    vowels.each do |vowel|
      if char == vowel
        is_vowel = true
        break
      end
    end

    is_vowel
  end

  puts count
end

不过,这并不短.我们可以使用的另一个好方法是 Enumerable#any?.它为数组中的每个项目评估给定的块,并在找到块返回 true 的任何项目时返回 true.使用它使我们的代码超短,但仍然可读:

That's not much shorter, though. Another great method we can use is Enumerable#any?. It evaluates the given block for each item in the array and returns true upon finding any item for which the block returns true. Using it makes our code super short, but still readable:

def count_vowels(string)
  chars = string.chars
  vowels = %w[ a e i o u ]

  count = chars.count do |char|
    vowels.any? {|vowel| char == vowel }
  end

  puts count
end

(在这里你会看到我加入了另一个常见的 Ruby 习语,即用于创建数组的百分比文字"符号:%w[ aeiou ].这是创建数组的常用方法没有所有引号和逗号的字符串.您可以 在此处阅读更多相关信息.)

(Here you'll see I threw in another common Ruby idiom, the "percent literal" notation for creating an array: %w[ a e i o u ]. It's a common way to create an array of strings without all of those quotation marks and commas. You can read more about it here.)

另一种做同样事情的方法是使用 Enumerable#include?,如果数组包含给定的项目,则返回 true:

Another way to do the same thing would be to use Enumerable#include?, which returns true if the array contains the given item:

def count_vowels(string)
  vowels = %w[ a e i o u ]  
  puts string.chars.count {|char| vowels.include?(char) }
end

...但事实证明,String 也有一个 include? 方法,所以我们可以这样做:

...but as it turns out, String has an include? method, too, so we can do this instead:

def count_vowels(string)
  puts string.chars.count {|char| "aeiou".include?(char) }
end

还不错!但我把最好的留到了最后.Ruby 有一个很棒的方法,叫做 String#计数:

Not bad! But I've saved the best for last. Ruby has a great method called String#count:

def count_vowels(string)
  puts string.count("aeiou")
end

这篇关于尝试使用 Ruby while 循环查找字符串的元音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆