Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> Doing this generally in Ruby I think is impossible

Not so much. At least with views over most Enumerables, its quite possible in Ruby -- that's the whole reason that Enumerable::Lazy exists.

The existing File class doesn't quite support it because of the way its iterators are implemented (particularly, they are one way) but the class is easily extended to allow it, e.g.:

  class RewindFile < File
    def each
      rewind
      each_char {|x| yield x}
    end
  end
 
Then you can create a synced view that has the character positions of the newlines in a file like this:

  a = RewindFile.new "myfile.txt"
  c = a.lazy.each
            .with_index
            .find_all {|x,_| x=="\n"}
            .map {|_,y| y}


If I go `a=whatever` or `a[42]=whatever`, then `c` will not get updated if I have already consumed those values; I still need to "reset" c every time I update a.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: