我试图编写一个接受字符串的方法,然后查找至少包含两个元音的单词,并将它们添加到另一个数组中,如下所示:
anyString = "Today we had football for breakfast"
#=> "today", "football", "breakfast"
如果这是另一种语言,我会做几个for循环,然后在计数器达到两个以上时添加单词。我想知道在Ruby中最简单的方法是什么。我试图在算法方面做得更好。有人可以提出什么建议吗?
答案 0 :(得分:5)
"Today we had football for breakfast"
.downcase.scan(/\w*[aeiou]\w*[aeiou]\w*/)
#=> ["today", "football", "breakfast"]
如果你想将其概括为"至少n个元音,"然后用
替换正则表达式/(?:\w*[aeiou]){n}\w*/
答案 1 :(得分:3)
我会使用String#count
方法。
str = "Today we had football for breakfast"
str.downcase.split.select { |s| s.count("aeiou") > 1 }
# => ["today", "football", "breakfast"]
答案 2 :(得分:2)
你正在考虑像C这样的命令式语言。这将是一种更为Rubyesque的方式:
anyString.downcase.split.select {|word| word.scan(/[aeiou]/).size >= 2 }
答案 3 :(得分:1)
str = "Today we had football for breakfast"
str.downcase.split.select { |w| w.gsub(/[^aeiou]/,'').size > 1 }
#=> ["today", "football", "breakfast"]
我使用了downcase
而不是(/[^aeiou]/i
,因为问题("Today"
)中给出的示例表明要收集缩小的字词。
答案 4 :(得分:0)
其他变种
anyString.downcase.split(' ').select { |word| word.match(/.*[aeiou].*[aeiuo].*/) }
答案 5 :(得分:0)
any_string.split.select { |w| w.scan(/[aeiou]/i).size > 1 }
=> ["Today", "football", "breakfast"]