我已经在各处搜索,但似乎找不到我需要的示例。我正在尝试学习Ruby并编写一个简单的脚本。用户被提示输入字母,这些字母被加载到数组中。然后脚本会遍历一个包含许多单词的文件,并提取包含数组中内容的单词。我的问题是它只能按照数组的顺序提取单词。例如...
characterArray = Array.new;
puts "Enter characters that the password contains";
characters = gets.chomp;
puts "Searching words containing #{characters}...";
characterArray = characters.scan(/./);
searchCharacters=characterArray[0..characterArray.size].join;
File.open("dictionary.txt").each { |line|
if line.include?(searchCharacters)
puts line;
end
}
如果我使用这段代码并输入“dog”,脚本将返回 dog doggie 但我需要输出结果返回单词,即使它们不是按相同的顺序。比如... dog doggie rodge 对于代码混乱的问题感到抱歉。就像我说的还在学习中。感谢您的帮助。
PS. 我也尝试过这个...
File.open("dictionary.txt").each { |line|
if line =~ /[characterArray[0..characterArray.size]]/
puts line;
end
}
但是这会返回所有包含用户输入的任意字母的单词。
"dog"
,而是存储为'd','o','g'
并检查搜索数组中的每个字母是否在您正在查找的单词中。 - Hunter McMillen