Reputation: 21
I'm a newbie! I have a text file that contains lines and lines of text. I want to try to create a code that only allows the lines that have the phrase "larry.bird" show while the others are deleted. This is my current code...
File.open("HM.txt").each do |line|
puts line
if line.include? "larry.bird"
puts "larye.bird " + line
end
end
File.readlines('HM.txt') do |li|
puts li if (li['larry.bird'])
end
If you can help me out, that would be awesome!
Upvotes: 0
Views: 623
Reputation: 70277
You're pretty close. You're opening and reading the file correctly; you're just accidentally printing every line before performing the check. The puts line
on the second line of your code is ensuring that this occurs.
File.open("HM.txt") do |file|
file.each_line do |line|
if line.include? "larry.bird"
puts "larry.bird " + line
end
end
end
We can also shorten one-line if statements in Ruby, using suffix notation that often makes code more concise.
File.open("HM.txt") do |file|
file.each_line do |line|
puts "larry.bird " + line if line.include? "larry.bird"
end
end
This is equivalent to the first example.
Upvotes: 1