1

I am working on creating a program which stores users in a textfile, and would love to delete/modify a line based on a keyword. This is the code I have right now for searching a keyword, which in return will print the whole line containing the keyword:

        keyword = File.readlines('skier_info.txt')
        matches = keyword.select { |name| name[/#{search}/i] }

I'm wondering how I can use this small bit of code to write every line from the textfile over to a new one, except for the one line I get from the "matches" variable.

2 Answers2

1

So you can already identify the line(s) you want to remove? That's 70% of the work. Almost there!

Now all you need to do is create a new file and write to it all lines from the existing file, except the ones you don't need. After you're done writing the new file, you can copy it over the old one.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
0

With the least amount of modification from your code :

keyword    = File.readlines('skier_info.txt')
no_matches = keyword.reject { |name| name[/#{search}/i] }

File.open('new_skier_info.txt','w+'){|out| out.puts no_matches}

reject is the opposite of select :

(1..10).reject{|x| x.even?}
=> [1, 3, 5, 7, 9]

If your input file is big and you don't want to read it all in memory :

File.open('new_skier_info.txt','w+') do |out| 
  File.foreach('skier_info.txt') do |line|
    out.puts line unless line =~ /#{search}/i
  end
end

You could also use grep -v in terminal ;)

Community
  • 1
  • 1
Eric Duminil
  • 52,989
  • 9
  • 71
  • 124