`
Hooopo
  • 浏览: 335268 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Using a String as a File in Ruby

    博客分类:
  • Ruby
阅读更多
编辑器不能用啦。。。
分享到:
评论
3 楼 Hooopo 2009-08-24  
irb(main):001:0> require 'stringio'
=> true
irb(main):002:0> s = StringIO.new
=> #<StringIO:0x2ced9a0>
irb(main):003:0> s << 'foo'
=> #<StringIO:0x2ced9a0>
irb(main):004:0> s << 'bar'
=> #<StringIO:0x2ced9a0>
irb(main):005:0> s.string
=> "foobar"
2 楼 Hooopo 2009-08-24  
>> s = StringIO.new
=> #<StringIO:0x3659d4>
>> s << 'foo'
=> #<StringIO:0x3659d4>
>> s << 'bar'
=> #<StringIO:0x3659d4>
>> s.pos
=> 6
>> s.rewind
=> 0
>> s.read
=> "foobar"
1 楼 Hooopo 2009-08-24  
require 'stringio'
str = StringIO.new %{This is a test of a string as a file. \r\n
                     And this could be another line in the file}

# Get a line
str.gets # => "This is a test of a string as a file. \r\n"

# Get the next 18 charaters
str.read(18) # => " And this could be"

# Seek to new position and read 7 more characters
str.pos = 59  # => 59
str.read(7) # => "another"

# Rewind the file and overwrite some of the existing text
str.rewind
str.write("Here's how to use")

# Rewind again and output the new contents
str.rewind
str.read # => "Here's how to use a string as a file.
     \r\n And this could be another line in the file"
str.eof? # => true

相关推荐

Global site tag (gtag.js) - Google Analytics