How to write to file when using Marshal::dump in Ruby for object serialization

前端 未结 1 1623
后悔当初
后悔当初 2020-12-17 06:24

Lets say I have the object line from class Line:

class Line
  def initialize point1, point2
    @p1 = point1
    @p2 = point2
  end         


        
相关标签:
1条回答
  • 2020-12-17 06:52

    Like this:

    class Line
      attr_reader :p1, :p2
      def initialize point1, point2
        @p1 = point1
        @p2 = point2
      end
    end
    
    line = Line.new([1,2], [3,4])
    

    Save line:

    FNAME = 'my_file'
    
    File.open(FNAME, 'wb') {|f| f.write(Marshal.dump(line))}
    

    Retrieve into line1:

    line1 = Marshal.load(File.binread(FNAME))
    

    Confirm it works:

    line1.p1 # => [1, 2]
    
    0 讨论(0)
提交回复
热议问题