Hey guys, need your help with a newbie problem! Thank You!


First line
Second line
Last line


rd_lines = []
input = gets
File.open(“sample.txt”) do |line_reader|
rd_lines = line_reader.readlines


rev_lines = rd_lines.find_all{|l|l.include?("#{input}")} 

#it prints only First line Second line

rev_lines = rd_lines.find_all{|ln|ln.include?(“line”)}
prints First line Second line Last line


puts rev_lines

loop {sleep 10}

It might be due to the newline character. Your file “sample.txt” may not have a newline marker after “Last line”, and so the last part is not matched.

When you write:

input = gets

Then “input” will receive the newline from gets as well as the string, so instead write:

input = gets.strip

(You can see the difference if you puts input.length afterwards.)

Thank you for help, it’s strange but this code is…valid.
Before to post I’ve tested it ten of time and it was only two string, but this morning I ran code again and it all ok
But anyway, thanks for help.

The strip is important though after gets. Try it by entering different search strings, like “lin” or “st”: without strip you won’t get any matches, but with strip you will.

See this irb session:

$ irb
2.7.2 :001 > a = gets
 => "line\n" 
2.7.2 :002 > b = gets.strip
 => "line" 

It’s work! Thanks!
Did you learn with books or just read ruby documentation?

I started to learn Ruby using the pickaxe book, but use Ruby documentation for specific classes and methods.

But solving problems like the one you had in this thread you learn from experience, by trying new things and making lots of mistakes.

Why are you promoting strip over chomp?

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