From: Ryan Davis Date: 2010-10-15T06:32:54+09:00 Subject: Re: from a String. On Oct 14, 2010, at 11:03 , Huw Taylor wrote: > If I were to have this: > > class Hew > def initialize(string) > @string = string > end > def other_method > end > end > > a = Hew.new("Broown Cew") > => # > > b = a.to_s > => "#" > > My question is: Is there anyway to get the class (and its info) from b > (i.e what is now a string)? > > I see that changing it to a string loses the @string = "Broown Cew" bit. > :/ There are two potential questions hidden in this problem: Q1) How do I make the string representation of my object more readable? A1) Define your own #to_s: class Hew def initialize(string) @string = string end def to_s "Hew new #{@string}" end end cew = Hew.new("Broown Cew") p cew # => # puts cew # => Hew new Broown Cew Q2) How do I get an object back from a string representation? A2) Don't use to_s to get a string representation, use YAML, JSON, Marshal, or something else equally suited to serialize and deserialize your object into a readable presentation: require 'yaml' s = cew.to_yaml puts s # => # --- !ruby/object:Hew # string: Broown Cew p YAML.load(s) # => #