I want Ruby to write the contents of the variable to a file.

Asked 2 years ago, Updated 2 years ago, 31 views

How can Ruby temporarily write the contents of a variable to a file?
We handle hash or array, and we used to write it in JSON and parse it when we needed it, but as the capacity increases, it takes a lot of time to parse it.

Is there a faster way to write and load than JSON?

ruby

2022-09-30 18:29

2 Answers

Why not use MessagePack to serialize each object? The usage can be found in GitHub, but basically (by gem install msgpack beforehand):

require'msgpack'
obj = 'Hello'
packed=obj.to_msgpack#Furthermore, write to a file, etc.
unpacked=MessagePack.unpacked


2022-09-30 18:29

How about PSTORE?

require 'pstore'
db=PSstore.new("/tmp/foo")
db.transaction do
  pdb.root#=>[ ]
  ary=db["root"]=[1,2,3,4]
  ary[0] = [1,1.5]
end

db.transaction do
  pdb["root"]#=>[1,1.5], 2, 3, 4]
end

https://docs.ruby-lang.org/ja/latest/class/PStore.html


2022-09-30 18:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.