Implicitly convert Symbols to Strings?

J

John Mair

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
 
R

Robert Klemme

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

The following does not work for example:

=A0 =A0eval:)self) #=3D> 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:

=A0 =A0class Symbol
=A0 =A0 =A0def to_str
=A0 =A0 =A0 =A0to_s
=A0 =A0 =A0end
=A0 =A0end

Then it works:

=A0 =A0eval:)self) #=3D> 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
=3D> 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
=3D> 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
=3D> 398

Kind regards

robert

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

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
473,965
Messages
2,570,148
Members
46,710
Latest member
FredricRen

Latest Threads

Top