Ruby scope of DATA after __END__

前端 未结 2 893
傲寒
傲寒 2021-01-01 18:42

I\'m using this Ruby trick with __END__ and DATA to put some data inside my program file:

class Foo
  def initialize()
    puts DAT         


        
相关标签:
2条回答
  • 2021-01-01 19:00

    DATA is the same. You would get the same output if instead of doing Foo.new you would do DATA.read a second time.

    This is because after the first read DATA (which is an IO) has reached the end of the stream, so any further reads will return an empty string, unless you append additional data to DATA or rewind DATA to the beginning of the stream.

    Edit: To seek back to the point right after the __END__ you have to read DATA.pos before performing any reading on DATA and then restore pos to that value after reading. The easiest solution is probably just doing FOO = DATA.read at the beginning of the script and then using FOO.

    0 讨论(0)
  • 2021-01-01 19:01

    rewind DATA first, because it's a stream.

    class Foo
      def initialize()
        DATA.rewind
        puts DATA.read.inspect
      end
    end
    puts DATA.read.inspect
    Foo.new
    __END__
    test
    
    0 讨论(0)
提交回复
热议问题