为什么说"`写&#39 ;:封闭流(IOError)"

时间:2017-11-10 17:23:21

标签: ruby io

我希望能够从我拥有的json中获取一个值,并将其放在另一个文件中,然后将其他值传递给另一个文件。这是我的代码:

somefile = File.open("employee_info.txt", "w")
File.open("employee_api_info.txt") do |file|
  file.each_line do |line|
    url = URI(line)
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true

    request = Net::HTTP::Get.new(url)
    request['Accept'] = 'application/vnd.pagerduty+json;version=2'
    request['Authorization'] = "Token token=#{token.chomp}"

    response = http.request(request)
    # puts response.body

    data=response.body
    jdoc = JSON.parse(data)

    somefile.puts "Employee Name: " + jdoc["user"]["name"].gsub(/\w+/, &:capitalize).gsub(/[.]/, ' ')
    somefile.puts "Employee Email: " + jdoc["user"]["email"]
    somefile.puts "Time Zone: " + jdoc["user"]["time_zone"]
somefile.close

    anotherfile = File.open("employee_phone_api.txt", "w+")
    jdoc.fetch("user").fetch("contact_methods").each do |contact|
      anotherfile.puts contact["self"]
    anotherfile.close
    end
  end
end

当我通过终端运行它总是返回...

`write': closed stream (IOError)
    from PagerDutyOncall.rb:93:in `puts'
    from PagerDutyOncall.rb:93:in `block (2 levels) in <main>'
    from PagerDutyOncall.rb:92:in `each'
    from PagerDutyOncall.rb:92:in `block in <main>'
    from PagerDutyOncall.rb:69:in `open'
    from PagerDutyOncall.rb:69:in `<main>'

有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

由于缩进无政府状态并使用手动打开/关闭,我认为您已经创建了此问题。这是正确缩进的代码:

anotherfile = File.open("employee_phone_api.txt", "w+")
jdoc.fetch("user").fetch("contact_methods").each do |contact|
  anotherfile.puts contact["self"]
  anotherfile.close
end

请注意,anotherfile.close位于循环内。这是你的问题。通过正确嵌套来修复它:

File.open("employee_phone_api.txt", "w+") do |af|
  jdoc.fetch("user").fetch("contact_methods").each do |contact|
    af.puts contact["self"]
  end
end

如果您使用ruby -w运行此操作,您应该收到有关不一致缩进的警告,这有助于首先避免此类问题。请记住:干净的代码使得肮脏的错误更加明显。