⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 14 - pretending a string is a file.rb

📁 O Reilly Ruby Cookbook source code
💻 RB
字号:
require 'stringio's = StringIO.new %{I am the very model of a modern major general.I've information vegetable, animal, and mineral.}s.pos                                 # => 0s.each_line { |x| puts x }# I am the very model of a modern major general.# I've information vegetable, animal, and mineral.s.eof?                                # => trues.pos                                 # => 95s.rewinds.pos                                 # => 0s.grep /general/# => ["I am the very model of a modern major general.\n"]#---s = StringIO.news.write('Treat it like a file.')s.rewinds.write("Act like it's")s.string                             # => "Act like it's a file."require 'yaml's = StringIO.newYAML.dump(['A list of', 3, :items], s)puts s.string# --- # - A list of# - 3# - :items#---def make_more_interesting(io)  io << "... OF DOOM!"endmake_more_interesting("Cherry pie")     # => "Cherry pie... OF DOOM!"open('interesting_things', 'w') do |f|  f.write("Nightstand")  make_more_interesting(f)endopen('interesting_things') { |f| f.read }# => "Nightstand... OF DOOM!"#---poem = %{The boy stood on the burning deckWhence all but he had fledHe'd stayed above to wash his neckBefore he went to bed}#---output = open("poem", "w")output.write(poem)output.closeinput = open("poem")#---poem.grep /ed$/# => ["Whence all but he had fled\n", "Before he went to bed"]input.grep /ed$/# => ["Whence all but he had fled\n", "Before he went to bed"]#---input.grep /ed$/                           # => []input.rewindinput.grep /ed$/# => ["Whence all but he had fled\n", "Before he went to bed"]#---def fifth_byte(file)  file.seek(5)  file.read(1)endfifth_byte("123456")# NoMethodError: undefined method `seek' for "123456":Stringfifth_byte(StringIO.new("123456"))          # => "6"#---def file_operation(io)  io = StringIO(io) if io.respond_to? :to_str && !io.is_a? StringIO  #Do the file operation...end#---s = StringIO.news << "A string"s.reads << ", and more."s.rewinds.read                                # => "A string, and more."#---

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -