繁体   English   中英

如何在文本文件中搜索字符串,然后打印/返回/输出在Ruby中作为数字找到的文件的哪一行

[英]How do I search a text file for a string and then print/return/put out what line of the file it was found on as a number in Ruby

因此,我想使用从中得到的数字:

line = answer to question 
database.read.lines[line]

数据库是我正在搜索的文本文件。

您也可以这样操作:

text_to_find = 'some random text' # use gets method to take input from user
text_found_at_index = database.readlines.index{|line| not line[text].nil? }

希望这是您所需要的:)

我会尝试这样的事情:

query = gets.chomp
database.each_line.with_index do |line, index|
  if line.include?(query)
    puts "Line #{index}: #{line}" 
  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM