From: Michael Edgar Date: 2011-06-21T03:17:51+09:00 Subject: Re: What about Object#to_ruby ? On Jun 20, 2011, at 2:02 PM, Bernard Lambeau wrote: > Thanks a lot for your responses. I suspect that my question was not that > clear, though. > > I'm not really looking or Marshal or YAML or JSON dump format, but for a > method > to print a ruby *literal* (I should have called it to_ruby_literal) from a > ruby value, > where it makes sense. The goal is to ease human-readable ruby code > generation, > I must add. Nowadays, using inspect works for all but a few basic values: It sounds like you're essentially talking about a marshal format that *is* Ruby code. Something along the lines of this, without procs, singleton classes, no cyclic references (ruby 1.9), etc: class Object def to_ruby_literal str = "#{self.class.name}.allocate.tap do |obj|\n" instance_variables.each do |ivar| str << "obj.instance_variable_set(#{ivar}, #{instance_variable_get(ivar).to_ruby_literal})\n" end str << "end" end end [TrueClass, FalseClass, NilClass, String, Integer, Float].each do |klass| klass.class_eval do alias_method :to_ruby_literal, :inspect end end Usage: class A def initialize(x, y, z) @x, @y, @z = x, y, z end end puts A.new(1.3, "hello", false).to_ruby_literal A.allocate.tap do |obj| obj.instance_variable_set(@x, 1.3) obj.instance_variable_set(@y, "hello") obj.instance_variable_set(@z, false) end Michael Edgar adgar@carboni.ca http://carboni.ca/