简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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