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

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‘mynewfile.txt’, ‘w’)‘mynewfile.txt’, ‘a’) do |f1|
f1.puts “00834 tue z0sdf”
f1.puts “01230 wed z0sdf”
f1.puts “34234 tue wet0f”

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

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

I’m not sure of what you are trying to accomplish in your code, but if
want to assign varWed the lines that contain ‘wed’, I think you should
something like this:‘mynewfile.txt’, ‘r’) do |f|
f.each_line do |line|
varWed << line if line =~ /wed/

Or if you still want to use find method:‘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/ }

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

Yaser S.

Thanks Yaser -MC

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs