Concerning the #to_* convention

Howdy partners! I’m having a bit of fun writing a Ruby XML document
object model (yes, I’m aware of the fact that there already exists such
models), and I’m using #to_* throughout the code. I’m just wondering if
a #to_* method always should return a copy of the receiver, in the
format specified by * (e.g. str',i’), or if it’s okay to just pass a
reference to the receiver itself?

Consider this:

class Namespace
def to_xml_ns
self # should this be a copy?
end
end

class Element < Node
def initialize(opts = {})
if opts[:namespace]
# namespace' quacks like a Namespace object if opts[:namespace].respond_to? :to_xml_ns # I'd like a Namespace object in @namespace. @namespace = opts[:namespace].to_xml_ns #namespace’ quakcs like a String object
elsif opts[:namespace].respond_to? :to_str
@namespace = Namespace.new(:uri => opts[:namespace].to_str,
opts[:prefix])
end
end
end
end

I hope you can give me a hint of what the best practice is.

Cheers,
Daniel

“D” == Daniel S. [email protected] writes:

D> I hope you can give me a hint of what the best practice is.

I don’t know what is the best practice but you can ask ruby

moulon% ruby -e ‘a = [1, 2]; b = a.to_a; p a.object_id==b.object_id’
true
moulon%

moulon% ruby -e ‘a = “12”; b = a.to_s; p a.object_id==b.object_id’
true
moulon%

Guy Decoux

ts wrote:

moulon% ruby -e ‘a = “12”; b = a.to_s; p a.object_id==b.object_id’
true
moulon%

Guy Decoux

Sweet! Thanks!

Cheers,
Daniel

Daniel S. wrote:

moulon% ruby -e ‘a = “12”; b = a.to_s; p a.object_id==b.object_id’
Daniel

Those two examples are returning the same object because it is already
in the desired form. If it is actually a change, you will get a new
object:

irb(main):001:0> a = 12
=> 12
irb(main):002:0> b = a.to_s
=> “12”
irb(main):003:0> a.object_id
=> 25
irb(main):004:0> b.object_id
=> -605442624

-Justin