Ruby text

Soldato
Joined
24 Nov 2002
Posts
16,378
Location
38.744281°N 104.846806°W
Using Regexp one can locate a string within a text file I want... however, how do I copy the data from the following line?

E.g.

#Monkey's Name:
Gregory

I would want to extract Gregory, not "#Monkey's Name:"....

I know it's simple but I can't thinK!
 
I'm a ruby beginner, so there's probably better ways, but I think this works ok :

Code:
file = File.new("input.txt", "r")
while (line = file.gets)
        if line.match(/^#Monkey's Name:/)
        then
                result = file.gets
                break
        end
end
result = Gregory
 
Cool!

How would I amend the above so that it would cope for any "# Variable :".

I.e. it would read the entire file and store the line under each "# Variable :" in tab delimindated format.

So,

# Variable1:
blah1

# Variable2:
blah2

# Variable3:
blah3

Would merely become "blah1 blah2 blah3".
 
Code:
file = File.new("input.txt", "r")
result = "";
while (line = file.gets)
        if line.match(/^# Variable/)
        then
                if (result == "")
                        result = file.gets.chomp;
                else
                        result += "\t" + file.gets.chomp;
                end
        end
end
puts result
 
Okay... new problem.

It appears that it isn't JUST the single line after the # Variable..

It could be:

# Variable1:
blah

#Variable2:
blah
bob
dee

#Variable3:
etc..

So I suppose the logical thing is to only extract the text 'between' the #'s?
 
Just keep reading lines and appending, until you read a blank line. Then abort the inner loop and read lines in the outer loop until you find a "# Variable" line.
 
Back
Top Bottom