Ruby--ファイル読み書き、ファイバー

# 書き込み
File.open("yamazon.txt", "w") {|file| file.puts "hello";file.puts "a"}

# 書き込み 追記
File.open("yamazon.txt", "a") {|file| file.puts "h i j k";file.puts "a hello"}

# ファイルオープン 改行区切りで読み込み表示
File.open("./yamazon.txt") do |file|
file.each_line("\n") {|line| p line}
end

# 上と同じ
File.open("yamazon.txt","r") {|file| file.each_line {|line| p line}}
# 正確には
File.open("yamazon.txt","r") {|file| file.each_line("\n") {|line| p line}}

# 上と同じ
File.foreach("./yamazon.txt") {|line| p line}
# 正確には
File.foreach("./yamazon.txt","\n") {|line| p line}


# 1つの文字列として読み込み
str= IO.read("yamazon.txt")


# 出てくる単語を数えるFiber
words = Fiber.new do
  File.foreach("./yamazon.txt") do |line|
    line.scan(/\w+/) do |word|
      Fiber.yield word.downcase
    end
  end
end

counts = Hash.new(0)
while word = words.resume
  counts[word] += 1
end
counts

# => {"hello"=>2, "a"=>2, "h"=>1, "i"=>1, "j"=>1, "k"=>1}