Forum: Ruby Concerning the #to_* convention

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Daniel S. (Guest)
on 2005-12-13 19:18
(Received via mailing list)
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
ts (Guest)
on 2005-12-13 19:39
(Received via mailing list)
>>>>> "D" == Daniel S. <removed_email_address@domain.invalid> 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
Daniel S. (Guest)
on 2005-12-13 20:30
(Received via mailing list)
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
Justin C. (Guest)
on 2005-12-14 22:28
(Received via mailing list)
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
This topic is locked and can not be replied to.