Previous ToC Up Next

3. Using the to_s Method

3.1. xxx

aha:

 require "old_vector.rb"
 
 class Body
 
   TAG = "particle"
 
   attr_accessor :mass, :pos, :vel, :acc, :type
 
   def initialize(mass = 0, pos = Vector[0,0,0], vel = Vector[0,0,0])
     @mass, @pos, @vel = mass.to_f, pos.to_v, vel.to_v
     @type = nil
   end
 
   def to_s(precision = 16, base_indentation = 0, additional_indentation = 2)
     subtag = if @type then " "+@type else "" end
     indent = base_indentation + additional_indentation
     return " " * base_indentation + "begin " + TAG + subtag + "\n" +
       mass.to_s("mass", precision, indent) + "\n" +
       pos.to_s("position", precision, indent) + "\n" +
       vel.to_s("velocity", precision, indent) + "\n" +
       " " * base_indentation + "end" + "\n"
   end
 
   def write(file = $stdout, precision = 16,
             base_indentation = 0, additional_indentation = 2)
     file.print to_s(precision, base_indentation, additional_indentation)
   end
 
 end

aha:

 : inccode: .vector.rb
aha!

Note: to_f and to_v in initializer. Let them find the bug themselves!

Let us run the same test as before:

 require "iobody2.rb"
 
 b = Body.new(1, [2,3], [4.5, 6.7])
 b.write
And here is the result:

 |gravity> ruby test.rb
 begin particle
   mass =    1.0000000000000000e+00
   position =    2.0000000000000000e+00   3.0000000000000000e+00
   velocity =    4.5000000000000000e+00   6.7000000000000002e+00
 end
and also the more complex test:

 require "iobody2.rb"
 
 b = Body.new(1, [2,3], [4.5, 6.7])
 b.write($stdout, 4, 16, 4)

 |gravity> ruby test.rb
                 begin particle
                     mass =    1.0000e+00
                     position =    2.0000e+00   3.0000e+00
                     velocity =    4.5000e+00   6.7000e+00
                 end
Previous ToC Up Next