Opening/reading a text file - how do u use .find method?


#1

Here I am creating a text file, writing to the text file and then
opening the text file to search for one of the lines that I just
inserted this line contains ‘wed’.

My issue is that when I try to search the file using the .find and a
regular expression the file does not even enter my if statement. (This
is very beginner level I know) What do you think or suggest that I am
doing wrong here? MC

File.open(‘mynewfile.txt’, ‘w’)

File.open(‘mynewfile.txt’, ‘a’) do |f1|
f1.puts “00834 tue z0sdf”
f1.puts “01230 wed z0sdf”
f1.puts “34234 tue wet0f”
end

##-----> Here is my troubled code…
File.open(‘mynewfile.txt’, ‘r’) do |f1|
f = File.new(“mynewfile.txt”)
newline = f.each {|line| puts “#f.lineno}: #{line}”}
if f.each{|line| puts “#f.lineno}: #{line}”}.find =~ /wed/
varWed = newline
end
end


#2

Not that f.each{|line| puts “#f.lineno}: #{line}”}.find returns nil, and
nil
=~ /wed/ returns false. Therefore, any code inside that if statement
won’t
get executed.

I’m not sure of what you are trying to accomplish in your code, but if
you
want to assign varWed the lines that contain ‘wed’, I think you should
do
something like this:

File.open(‘mynewfile.txt’, ‘r’) do |f|
f.each_line do |line|
varWed << line if line =~ /wed/
end
end

Or if you still want to use find method:

File.open(‘mynewfile.txt’, ‘r’) do |f|
varWed << f.find_all { |line| line =~ /wed/ }.to_s
# If you only need the 1st line that contains ‘wed’, use:
# varWed = f.find { |line| line =~ /wed/ }
end

BTW, I didn’t know about find method before, and I was wondering from
where
do File objects get it in the first place. But now I know, thanks to
your
question :slight_smile:

Regards,
Yaser S.


#3

Thanks Yaser -MC