简体   繁体   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

So, I want to use the number I get from it in this: 因此,我想使用从中得到的数字:

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

Database being the text file I am searching in. 数据库是我正在搜索的文本文件。

You can also do it this way : 您也可以这样操作:

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? }

Hope, this is what you require : ) 希望这是您所需要的:)

I would try something like this: 我会尝试这样的事情:

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.

相关问题 如何在Ruby中打印文本文件的每一行? - How do I print each line of a text file in Ruby? 如何在另一个文件中搜索一个文件的字符串并在 ruby​​ 中打印匹配项的行号? - How to search strings of one file in another file and print line number of the match in ruby? 如果使用Ruby找到字符串,如何从$ stdout中搜索特定字符串并将整个$ stdout存储在文本文件中? - how to search particular string from $stdout and store whole $stdout in text file if string is found using Ruby? Ruby在文本文件中找到一个字符串,然后输出在其上找到的行 - Ruby find a string in a text file and output the line it's found on 从文本文件中搜索字符串并删除该行RUBY - search a string from a text file and delete that line RUBY 从文件Ruby中打印最长的行 - Print longest line out of a file Ruby Ruby - 读取文件并打印行号 - Ruby - Read file and print line number 如何用在Ruby文本文件中写入的每一行上找到的文件内容替换从控制台获取的URL中找到的特定字符串? - How to replace a particular string found in URL taken from console with file content found on each line written in text file in Ruby? 如何打印字符串中每行的行号? - How do I print the line number of each line in a string? 如何在包含TAB字符的Ruby文件中打印出行? - How do I print out lines in a Ruby file that contains TAB character?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM