ruby 文件I / O.

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby 文件I / O.相关的知识,希望对你有一定的参考价值。

#
fname = "sample.txt"
somefile = File.open(fname, "w")
somefile.puts "Hello file!"
somefile.close
require 'rubygems'
require 'rest-client'
require 'open-uri'

hamlet_url = "http://ruby.bastardsbook.com/files/fundamentals/hamlet.txt"

# Create the Hamlet file
File.open("hamlet.txt", "w") do |file|
  file.write(RestClient.get(hamlet_url))
end

# Print every 42nd line
File.open("hamlet.txt", "r").readlines.each_with_index do |line, index|
  if ((index + 1) % 42 == 0)
    puts line
  end
end

# Solution (alternate)
  # url = "http://ruby.bastardsbook.com/files/fundamentals/hamlet.txt"
  # local_fname = "hamlet.txt"
  # File.open(local_fname, "w"){|file| file.write(open(url).read)}

  # File.open(local_fname, "r") do |file|
  #    file.readlines.each_with_index do |line, idx|
  #       puts line if idx % 42 == 41
  #    end   
  # end

# Print only Hamlet's lines
file = File.open("hamlet.txt", "r")
while !(file.eof?)
  puts file.readline.scan(/^\s\s(Ham).+/)
end
require 'rubygems'
require 'rest-client'
require 'open-uri'

# Write to a file
File.open("wiki-page.html", "w") do |file|
  file.write "http://en.wikipedia.org/"
end

# Get / Fetch a file (from the web)
File.open("wiki-page-actual.html", "w") do |file|
  file.write(RestClient.get("http://en.wikipedia.org"))
end

# Read a file
contents = File.open("wiki-page.html", "r") { |file| file.read }
puts contents
print "\n"

# Readlines
File.open("sample.txt").readlines.each { |line|
  puts line
}
print "\n"

# Readline
file = File.open("sample.txt", "r")
while !(file.eof?)
  line  = file.readline
  puts line
end
print "\n"

# Get / Fetch a file (from the web) then read it.
url = "http://ruby.bastardsbook.com/files/fundamentals/hamlet.txt"
puts open(url).readline
print "\n"

以上是关于ruby 文件I / O.的主要内容,如果未能解决你的问题,请参考以下文章

python Python中的文件I / O.

text 带有Colaboratory Jupyter笔记本的Google Drive文件I / O.

c_cpp CPP - 教程012 - 操作员重载和文件I / O.

markdown shell I / O.

java 控制台I / O.

python Python - pickcle I / O.