使用Ruby计算并排字母的最大数量

时间:2012-01-14 21:26:34

标签: ruby regex string

我们如何获得并排的最大字母数?

例如,如果我们计算每个并排的最大字母a

"Muhahaha, hello world!!!!! Aaaaaaaa" # => 7
"fuu" # => 0
"foobar" # => 1
"aaa bbb ccc" # => 3
"aa bb cc aaaaa ff" # => 5

我正在使用Ruby 1.9.3。根据String类,我认为已经有一种方法可以做到这一点。也许Regexp类可能更有用。

你觉得有一种性感的方式吗?感谢任何建议。

2 个答案:

答案 0 :(得分:5)

我的方式是:

"Muhahaha, hello world!!!!! Aaaaaaaa".scan(/a+/).max.length #=> 7

或者如果那不起作用(但它应该)

"Muhahaha, hello world!!!!! Aaaaaaaa".scan(/a+/).sort.last.length #=> 7

答案 1 :(得分:1)

# returns the longest stretch of the same word character
str = "Muhahaha, hello world!!!!! Aaaaaaaa"
str.scan(/\w/).to_set.map { |c| str.scan(/#{c}+/).max }.sort_by(&:length).last.length