Forum: Ruby opening/reading a text file - how do u use .find method?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Cf63da956b6ba955687a2f2f262928cb?d=identicon&s=25 Mmcolli00 Mom (mmcolli00)
on 2008-12-02 15:45
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
B09f4659460545e38ece34ddd0d96b46?d=identicon&s=25 Yaser Sulaiman (Guest)
on 2008-12-03 15:16
(Received via mailing list)
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 :)

Regards,
Yaser Sulaiman
Cf63da956b6ba955687a2f2f262928cb?d=identicon&s=25 Mmcolli00 Mom (mmcolli00)
on 2008-12-03 15:24
Thanks Yaser -MC
This topic is locked and can not be replied to.