class Hew
def initialize(string) @string = string
end
def other_method
end
end
a = Hew.new("Broown Cew")
=> #<Hew:0x40e8238 @string = "Broown Cew">
b = a.to_s
=> "#<Hew:0x40e8238>"
My question is: Is there anyway to get the class (and its info) from b
(i.e what is now a string)?
Maybe you're looking for ObjectSpace._id2ref
Unfortunately, the hex pointer shown by #inspect doesn't always map
directly to the object's object_id, and I think the algorithm to map it
varies with the version of ruby you're running
But here in principle is how you recover a reference to the object:
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
# => #<Hew:0x1001560c0 @string="Broown 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)
# => #<Hew:0x1004aa848 @string="Broown Cew">
···
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")
=> #<Hew:0x40e8238 @string = "Broown Cew">
b = a.to_s
=> "#<Hew:0x40e8238>"
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.