Bug #11772
closedImplicit conversion of Array in String interpolation does not call to_str
Description
While providing an example in https://bugs.ruby-lang.org/issues/10930#note-7 I found that the implicit changing of an Array calls to_s without trying to_str first. Isn't String interpolation "implicitly" converting items to strings?
class Array
def to_str
"Hello from Array!"
end
end
"#{[1,2,3,4,5]}"
# => [1, 2, 3, 4, 5]
I believe String interpolation should call to_str
before to_s
Updated by danielpclark (Daniel P. Clark) over 8 years ago
My main point here is that anything that happens within String interpolation is "implicitly" going to be a String. So shouldn't it call to_str
before to_s
on anything given?
class B
def to_str
"Hello from B"
end
end
"#{B.new}"
# => "#<B:0x00000001969078>"
Should work as this does.
class B
def to_s
"to_s"
end
end
"#{B.new}"
# => "to_s"
I also realize that having Ruby lookup two methods to_str
and then to_s
may slow it down and that we don't want to make it slower. Since Ruby is optimized for to_s
being called first I think it would be okay to have to_str
called second. Even though by definition you would think that an "implicit" method would be the first method called.
Updated by duerst (Martin Dürst) over 8 years ago
- Status changed from Open to Closed
As (implicitly) requested at ruby-core:71843.
Updated by danielpclark (Daniel P. Clark) over 8 years ago
class A
undef :to_s
def to_str
"hello world"
end
end
"#{A.new}"
#NoMethodError: undefined method `to_s' for #<A:0x00000000dbea70>
"" + A.new
# => "hello world"
Using +
to call to_str
feels like JavaScript.