Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (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)
Add Comment
Please, Sign In to add comment