Implicitly convert Symbols to Strings?

Is there a good reason why Symbols are not implictly converted to
Strings ?

The following does not work for example:

    eval(:self) #=> Error: can't convert Symbol to String

But if we do the following:

    class Symbol
      def to_str
        to_s
      end
    end

Then it works:

    eval(:self) #=> main

In my opinion this implicit conversion should happen and would be
useful in some circumstances. Why isn't this supported out of the box?

John

···

--
Posted via http://www.ruby-forum.com/.

Is there a good reason why Symbols are not implictly converted to
Strings ?

The following does not work for example:

eval(:self) #=> Error: can't convert Symbol to String

But you can do eval(x.to_s) for any type of x - including Symbols.

But if we do the following:

class Symbol
def to_str
to_s
end
end

Then it works:

eval(:self) #=> main

In my opinion this implicit conversion should happen and would be
useful in some circumstances. Why isn't this supported out of the box?

Because Symbols are not Strings. For example, assume you use a Symbol
in a place where a String is expected. The String is manipulated but
the changes go away because the modification was on an automatically
created temporary String and is lost without you noticing. Method
#to_str is really reserved only for classes that are String compatible
- and immutable Symbols aren't.

irb(main):001:0> ObjectSpace.each_object(Module){|m| p m if
m.instance_methods.include?(:to_str)}
NameError::message
String
=> 398

Take another example:

irb(main):002:0> ObjectSpace.each_object(Module){|m| p m if
m.instance_methods.include?(:to_int)}
Complex
Rational
Bignum
Float
Fixnum
Integer
Numeric
=> 398
irb(main):003:0> ObjectSpace.each_object(Module){|m| p m if
m.instance_methods.include?(:to_i)}
Complex
Rational
Process::Status
Time
File
ARGF.class
IO
Bignum
Float
Fixnum
Integer
String
NilClass
=> 398

Kind regards

robert

···

On Tue, Nov 2, 2010 at 3:36 AM, John Mair <jrmair@gmail.com> wrote:

--
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/