用红宝石计算元音中的元音

时间:2017-11-17 04:27:33

标签: ruby iteration

我的目标是返回给定字符串中的元音数量。我试过这段代码:

def count_vowels(string)
  vowels = ['a', 'e', 'i', 'o', 'u']
  chars_ary = string.split(//)
  ary_with_vowels = chars_ary.take_while {|letter| vowels.include?(letter)}
  return ary_with_vowels.length
end

它并没有通过大多数测试用例。我知道还有其他多种方法可以解决这个问题,但我想用我提供的代码解决它。

有人可以告诉我为什么这不起作用吗?

4 个答案:

答案 0 :(得分:6)

这种方式更容易:

S::S

答案 1 :(得分:5)

take_while这里是错误的方法。它从头开始,只要块返回一个真值,就“获取”元素。它会在您第一次遇到不是元音的字母时停止。

您希望select选择块返回真值的所有元素。

答案 2 :(得分:3)

让我们对几种方法进行基准测试。

require 'fruity'
require 'set'

SET_OF_VOWELS = %w| a e i o u |.to_set

def string_count(str)
  str.count('aeiou')
end

def set_include?(str)
  str.each_char.count { |c| SET_OF_VOWELS.include?(c) }
end

def use_hash(str)
  h = str.each_char.with_object(Hash.new(0)) { |c,h| h[c] += 1 }
  SET_OF_VOWELS.sum { |c| h[c] }
end

alpha = ('a'..'z').to_a

[1_000, 10_000, 100_000, 1_000_000].each do |n|

  puts "\nString length = #{n}"     
  str = Array.new(n) { alpha.sample }.join

  compare(
    string_count: -> { string_count(str) },
    set_include?: -> { set_include?(str) },
    use_hash:     -> { use_hash(str) }
  )
end    

结果如下。

String length = 1000
Running each test 1024 times. Test will take about 9 seconds.
string_count is faster than set_include? by 159x ± 1.0
set_include? is faster than use_hash by 37.999999999999986% ± 1.0%

String length = 10000
Running each test 128 times. Test will take about 11 seconds.
string_count is faster than set_include? by 234x ± 1.0
set_include? is faster than use_hash by 35.00000000000001% ± 1.0%

String length = 100000
Running each test 16 times. Test will take about 14 seconds.
string_count is faster than set_include? by 246x ± 1.0
set_include? is faster than use_hash by 35.00000000000001% ± 1.0%

String length = 1000000
Running each test 2 times. Test will take about 18 seconds.
string_count is faster than set_include? by 247x ± 1.0
set_include? is faster than use_hash by 34.00000000000001% ± 1.0%

答案 3 :(得分:-1)

尝试这样的事情,查看元音数组中的每个字符,并将其与字符串中的每个字符进行比较,如果条件为真,则将其与p进行比较。

def vowles(string)
arr = []
vowels = %w(a e i o u)
vowels.each do |x|
    if string.each_char { |letter| (arr << x) if x == letter }
    end
  end
  p "#{arr} has #{arr.count} vowels"
end
vowles("wwwweeeeeee")

或效率更高

def vowels(string)
  p string.scan(/[a e i o u]/).count
end
vowels("hello world")