简体   繁体   中英

Printing to file from Ruby pp

I'm parsing a JSON file in Ruby and want to output the results using pp to a file. How can I do that? Here's the code I'm trying:

require 'rubygems'
require 'json'
require 'pp'

json = File.read('players.json')
plyrs = JSON.parse(json)

File.open('plyrs.txt', 'a') { |fo| pp page, fo }

Try this

require 'rubygems'
require 'json'
require 'pp'

json = File.read('players.json')
plyrs = JSON.parse(json)

File.open('plyrs.txt', 'a') { |file| file.write(pp plyrs) }

More info available at the ruby documentation

require "rubygems" is redundant in Ruby >= 1.9.

require "json"
require "pp"

plyrs = JSON.load("players.json")
File.open("plyrs.txt", "a"){|io| io.write(plyrs.pretty_inspect)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM