The following code opens a text file does a little regex to match names and numbers. I do an IF so that I only match numbers greater than 0. When I try to puts the name and number, I only get the numbers and the name have become nil. If I puts the names (variable a) before the if statement, it is there. What am I doing wrong?
nf = File.open("textfile.txt")
nf.each do |b|
a = b.match(/([\S]+)name([\S]+)/)
c = b.match(/[0-9]+ numbers/)
c = c.to_s.split(/ /)
c = c[0].to_i
if c > 0
puts a
puts c
end
end
textfile looks like this:
My name is Mark
12432 numbers
My name is Joe
0 numbers
I want to be able to puts:
My name is Mark
12432 numbers
and not print out:
My name is Joe
0 numbers
Thanks in advance for your help
Well there are four lines. On lines 1 and 3 there is a name, so a will not be nil. However
c > 0will be false and thus nothing will be printed.On lines 2 and 4 there is no name, so
ais nil.Edit: Also
/([\S]+)name([\S]+)/will never actually match in your example file because “name” is surrounded by spaces (and\Smeans “not a space”).Edit2: Here’s a solution using
scan