Is it necessary to close StringIO in ruby?

后端 未结 5 674
眼角桃花
眼角桃花 2021-01-01 20:00

Do we need to close StringIO objects after usage in Ruby in order to free resources, like we do with the real IO objects?

obj = StringIO.new \"some string\"
         


        
5条回答
  •  有刺的猬
    2021-01-01 20:06

    In response to the other answers here: calling close won't help you save memory.

    require "stringio"
    sio = StringIO.new
    sio.print("A really long string")
    sio.close
    sio.string # => "A really long string"
    

    "A really long string" will stay around as long as sio does, close or no close.

    So why does StringIO have a close method? Duck typing. Providing close, and throwing an IOError if you try to read or write from it, ensures it acts like a real File object would. This is useful if you're using it as a mock object while unit testing.

提交回复
热议问题