My end goal is to compare values from a file to the records I'm pulling back from a database.
I have a text file with the following structure:
123,55,66
555,99,109
324,100,800
467,200,300
I then pull back records from a database and loop through them one by one.
sth.fetch do |row|
validate = "#{row[0]},#{row[20]},#{row[21]}"
names = File.readlines('results.txt')
matches = names.select { |name| name[/#{validate}/i] }
p "Result matches as expected: #{matches}"
end
so validate builds me the same format string as per the examples above... I then read all lines of the file and move them into an array and then compare. So this is great it gives me all matches but doesn't tell me rows that don't exist on the file?
So alternatively I tried
sth.fetch do |row|
File.open('results') do |f|
f.each_line do |line|
if line == validate
puts "detail: #{line}"
else
puts "detail: #{validate}"
end
end
end
end
But this then reads each line for every row and compares so it half achieves what I am after.
So I want to take my 'validate' string and read the contents of the file to see if a row matches and then print out it's a match. Alternatively if I pull back a record and it doesn't match the file then I just want one does not match message.
Thanks
I would try the following
names = File.readlines('results.txt').map(&:chomp)
sth.fetch do |row|
validate = "#{row[0]},#{row[20]},#{row[21]}"
# for direct compare
# if names.include?(validate)
# Or for Regexp
if names.grep(/#{validate}/i).any?
p "Result matches as expected: #{matches}"
else
p "Result does not matches as expected: #{matches}"
end
end
all_matches.uniq!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.