【问题标题】:What does the .rewind method do on a Tempfile in ruby?.rewind 方法对 Ruby 中的 Tempfile 有什么作用?
【发布时间】:2018-07-09 20:24:52
【问题描述】:

我浏览了 these docs 和 Google,似乎无法找到 .rewind 的用途,以及它与 .close 的区别,在使用 Tempfile 的情况下。

另外,为什么.read在倒带之前返回一个空字符串?

这是一个例子:

file = Tempfile.new('foo')
file.path      # => A unique filename in the OS's temp directory,
               #    e.g.: "/tmp/foo.24722.0"
               #    This filename contains 'foo' in its basename.
file.write("hello world")
file.rewind
file.read      # => "hello world"
file.close
file.unlink    # deletes the temp file

【问题讨论】:

    标签: ruby-on-rails ruby stringio


    【解决方案1】:

    倒带 - 在ruby docs了解更多信息

    IO#Close - 阅读更多关于ruby docs

    阅读 - 阅读更多关于ruby docs

    总结

    rewind
    将 ios 定位到输入的开头,将 lineno 重置为零。 Rewind 将行号重置为零

    f = File.new("testfile")
    f.readline   #=> "This is line one\n"
    f.rewind     #=> 0
    f.lineno     #=> 0
    f.readline   #=> "This is line one\n"
    

    IO#close
    关闭 ios 并将任何挂起的写入刷新到操作 系统。

    read([length [, outbuf]])

    从 I/O 流中读取长度字节。长度必须是非负整数或 nil。 如果长度为零,则返回一个空字符串(“”)。

    【讨论】:

    • 很棒的答案。谢谢!
    • 很高兴为您提供帮助
    • 我建议您链接到 Ruby 文档的相关部分,而不是复制其部分或全部内容。这样,如果读者已经知道文档内容,他们可以跳过链接。此外,如果没有链接,读者可能很难找到文档以进行更全面的阅读。例如,我建议“IO.close 关闭文件并清除所有挂起的写入。”。至少,将close 写成IO#close
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 2015-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多