How do I write a function, that will read the file and delete a line with a keyword that I input? to w or w+ instead of a, it deletes everything. Where is the problem?

"r" is the proper mode if you only want to read the file. "w" is if you want to just empty the file completely then write to it. "a"will append data on to the end of the file, which is useful sometimes. You don't need to keep the file open the whole time, and you can re-open a file using a different mode. Get the data in/out then close it again, right in the block you give when you open the file up.

Try this.

data ="example.txt", "r") {|f|"\n")}
# gets a string, then we split into an array on newlines so no chomp needed
p data.reject {|x| x =~ /#{ARGV[0]}/}
# p data is like puts data.inspect which is really useful sometimes
# ARGV[0] gets the first command line argument from when you open the file.

Put something simple in the example.txt file like, cat dog and pig or whatever else you like. Call the file from the command line with ruby example.rb cat with several different arguments, including things not in the file. Then call it with just ruby example.rb without any arguments.

Play around with the example code until you figure out how to represent your data structure and get rid of what you don't want in a safe way. Check this link for how to make use of split to convert your input data into neatly separated string entries in an array.

Don't worry about getting it into the file until you've worked out the rest. The simpler you try to do this, the faster it will go for you between attempts. Try to figure out what the code is doing and why. Check the documentation to help you, it's hard at first but it will save you a lot of misery later on. Also try to figure out things like, what's the most effective way to represent each entry of data once you have what you want out of it. That will help you write the logic that does stuff to the data before you put it back in a file.

/r/ruby Thread Parent