我有一个代码要求用户输入Cats或Dogs然后它会搜索一个包含Cats或Dogs字样的数组,然后将它们全部输出。
print "Cats or Dogs? "
userinput = gets.chomp
lines = [["Cats are smarter than dogs"],["Dogs also like meat"], ["Cats are nice"]]
lines.each do |line|
if line =~ /(.*?)#{userinput}(.*)/
puts line
end
end
所以如果我输入Cats。我应该得到两句话:
Cats are smarter than dogs
Cats are nice
你甚至可以更聪明地输入,我会得到
Cats are smarter than dogs
我严格地寻找使用正则表达式搜索数组或字符串的方法,并取出与表达式匹配的行/句子。
如果有人想知道,行数组最初来自一个文件,我将每一行转换为数组部分。
编辑:
哇,我在编码世界中走了多远。print "Cats or Dogs? "
userinput = gets.chomp
lines = [["Cats are smarter than dogs"],["Dogs also like meat"], ["Cats are nice"]]
lines.each do |linesInside|
linesInside.each do |line|
if line =~ /(.*?)#{userinput}(.*)/
puts line
end
end
end
花了5秒的时间来解决当时我花了多少时间才放弃的事情。
答案 0 :(得分:3)
试试这个
...
lines = ["Cats are smarter than dogs", "Dogs also like meat", "Cats are nice"]
regexp = Regexp.new(userinput)
selected_lines = lines.grep(regexp)
puts selected_lines
这是如何运作的?
grep
使用模式匹配过滤数组答案 1 :(得分:1)
当然,你可以在没有正则表达式的情况下这样做。
lines = ["Dogs are smarter than cats", "Cats also like meat", "Dogs are nice"]
print "Cats or Dogs? "
input = gets.chomp.downcase
如果input #=> "dogs"
,
lines.select { |line| line.downcase.split.include?(input) }
#=> ["Dogs are smarter than cats", "Dogs are nice"]
如果input #=> "cats"
,
lines.select { |line| line.downcase.split.include?(input) }
#=> ["Dogs are smarter than cats", "Cats also like meat"]
答案 2 :(得分:0)
由于您的数组是一个数组数组,因此您可以先调用flatten:
lines.flatten.grep(/#{userinput}/i)
i
用于不区分大小写的搜索,以便“狗”#39;比赛' Dogs'和'狗'。
如果您想要全字搜索:
lines.flatten.grep(/\b#{userinput}\b/i)
最后,如果您真的不需要数组数组,只需直接从您的文件中读取数组,或者使用File.readlines(f)
或File.foreach(f)
。