如何计算Ruby中字符串开头的连续辅音?

How to count consecutive consonants at beginning of a string in Ruby?

我仍在接受 Regex,并希望制定一个表达式来计算字符串开头连续辅音的数量。例如。 'Cherry' 会 return 2, 'hello' 1, 'schlepp' 4 等等。由于数字不是预先确定的(尽管英语可能对初始辅音有一些上限!)我需要一些灵活的表达方式,但我对如何编写它有点困惑。欢迎任何指点!

沿着这条线的东西会起作用:

>> 'Cherry'.downcase.split(/([aeiou].*)/).first.length
# => 2
>> 'hello'.downcase.split(/([aeiou].*)/).first.length
# => 1
>> 'schlepp'.downcase.split(/([aeiou].*)/).first.length
# => 4

这可行:

'Cherry'[/\A[bcdfghjklmnpqrstvwxyz]*/i].length #=> 2

正则表达式匹配字符串开头的零个或多个辅音。 String#[] returns the matching part and length 确定其长度。

您还可以通过 &&:

[a-z][^aeiou] 相交来更简洁地表达辅音字符 class
'Cherry'[/\A[a-z&&[^aeiou]]*/i].length #=> 2

另一种方法是从第一个元音到字符串末尾替换为空,然后取长度:

'Cherry'.gsub(/[aeiou].*$/,"").length

没有必要使用正则表达式。

CONSONANTS = (('a'..'z').to_a - 'aeiou'.chars).join
  #=> "bcdfghjklmnpqrstvwxyz"

def consecutive_constants(str)
  e, a = str.each_char.chunk { |c| CONSONANTS.include?(c.downcase) }.first
  e ? a.size : 0
end

consecutive_constants("THIS is nuts")       #=> 2
consecutive_constants("Is this ever cool?") #=> 0
consecutive_constants("1. this is wrong")   #=> 0

备注

enum = "THIS is nuts".each_char.chunk { |c| CONSONANTS.include?(c.downcase) }
  #=> #<Enumerator: #<Enumerator::Generator:0x000000010e1a40>:each>

我们可以通过应用 Enumerable#entries (or Enumerable#to_a):

查看该枚举器将生成​​的元素
enum.entries
  #=> [[true, ["T", "H"]], [false, ["I"]], [true, ["S"]], [false, [" ", "i"]],
  #    [true, ["s"]], [false, [" "]], [true, ["n"]], [false, ["u"]], [true, ["t", "s"]]]

继续,

  e, a = enum.first
    #=> [true, ["T", "H"]]
  e #=> true
  a #=> ["T", "H"]
  a.size
    #=> 2