ruby - 如何找到包含所有元音的同一数组的两个元素
问题描述
我想迭代给定的数组,例如:
["goat", "action", "tear", "impromptu", "tired", "europe"]
我想查看所有可能的配对。
所需的输出是一个新数组,其中包含所有对,组合包含所有元音。此外,这些对应连接为输出数组的一个元素:
["action europe", "tear impromptu"]
我尝试了以下代码,但收到错误消息:
No implicit conversion of nil into string.
def all_vowel_pairs(words)
pairs = []
(0..words.length).each do |i| # iterate through words
(0..words.length).each do |j| # for every word, iterate through words again
pot_pair = words[i].to_s + words[j] # build string from pair
if check_for_vowels(pot_pair) # throw string to helper-method.
pairs << words[i] + " " + words[j] # if gets back true, concatenade and push to output array "pairs"
end
end
end
pairs
end
# helper-method to check for if a string has all vowels in it
def check_for_vowels(string)
vowels = "aeiou"
founds = []
string.each_char do |char|
if vowels.include?(char) && !founds.include?(char)
founds << char
end
end
if founds.length == 5
return true
end
false
end