Concerning the #to_* convention

D

Daniel Schierbeck

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
 
T

ts

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
 
D

Daniel Schierbeck

ts said:
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

Sweet! Thanks!


Cheers,
Daniel
 
J

Justin Collins

Daniel said:
ts said:
"D" == Daniel Schierbeck <[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

Sweet! Thanks!


Cheers,
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,201
Messages
2,571,048
Members
47,646
Latest member
xayaci5906

Latest Threads

Top