Ruby Luva <noderat / hotmail.com> writes:

> The problem for me is that I do not know what the second value I am 
> looking for is... :)
>
> I am making an HTTP request to a site and I know one value to look for. 
> The value I am interested in changes but is always 2 lines above the 
> string I CAN find.
>
> This code works: #if I want to retrieve 'a'
>
> data = ['a','b','c']
> found = data.index('c')
> puts data[found-2]

Well if the data you want to extract is two lines above the line you
match, why didn't you say so sooner?  You told only us about "123" and
"yes"...

But on the same principle, you may keep a buffer of the last lines
seen to be able to go back easily:


(stack = "aaaaaaa
bbbbbbb
123 nay!
ccccccc
123 yeah!
ddddddd
yes yes
yes no
eeeeeee")
(target = "yes")
(previousLines = (CircularBuffer . new(2)))
(stack . each { |line|
   (line . chomp!)
   (if (line . include? target)
      (break)
    end)
   (previousLines . enter line)})
(printf "two lines before the target line is '%s'\n" , (previousLines . nth 1))



Here is for example a CircularBuffer that would do:

(class Node
   (attr_accessor :data,:previous,:next)
   (def initialize(data)
      (@data = data)
      (@previous = nil)
      (@next = nil)
    end)
end)

(class CircularBuffer
   (def initialize(maxSize)
      (@maxSize = maxSize)
      (@size = 0)
      (@tail = nil)
    end)
   (def enter(data)
      (if (@size == @maxSize)
         (@tail . data= data)
         (@tail = (@tail . next))
       elsif (@size == 0)
         (@tail = (Node . new data))
         (@tail . previous= @tail)
         (@tail . next=     @tail)
         (@size = 1)
       else
         (node = (Node . new data))
         (node . previous= (@tail . previous))
         (node . next=     @tail)
         (@tail . previous . next = node)
         (@tail . previous = node)
         (@size = (@size + 1))
       end)
    end)
   (def nth(index)
      (index = (index . modulo @maxSize))
      (cur = (@tail . previous))
      (while (0 < index)
         (cur = (cur . previous))
         (index = (index - 1))
       end)
       (cur . data)
    end)
end)



> Sadly I need it to work on a HTTP request so I store my data liek this:
>
> got = Array.new
> go = net::HTTP.new(a,b)

However, if your data is HTML or XML, this kind of data is structured,
and newlines are rather insignificant, so it's brittle to count lines
to find data there.  You should rather parse the html (there are Ruby
libraries to do that), and find your data "structurally".

-- 
__Pascal Bourguignon__