foreach.rb(file)
This Ruby code snippet reads and processes the contents of two files, foreach_b.txt
and foreach_a.txt
. It works as follows:
- It opens
foreach_b.txt
and iterates through each line in the file. - For each line from
foreach_b.txt
, it opensforeach_a.txt
and iterates through its lines. - During this nested iteration, it compares the current line from
foreach_b.txt
with each line fromforeach_a.txt
. - If it finds a matching line in both files (i.e., the lines are identical), it prints a message indicating that a match was found, including the matched line.
- Once a match is found, it stops checking further lines in
foreach_a.txt
for the current line fromforeach_b.txt
and moves on to the next line fromforeach_b.txt
.
Essentially, this code checks for common lines between the two files and reports each match.
Execution:
File.foreach('foreach_b.txt') do |line1|
File.foreach('foreach_a.txt') do |line2|
if line1.eql?(line2)
puts("MATCHED: #{line1}")
break
end
end
end
MATCHED: 9
MATCHED: 2
MATCHED: 6
#=> nil
Executed with Ruby 3.3.6