I want to get String object out of ActiveSupport::SafeBuffer. Method to_s returns the same type ActiveSupport::SafeBuffer. Only to_sym.to_s returns String, but this is more of a hack. Here's my console playing:
irb(main):008:0> s = ActiveSupport::SafeBuffer.new("asdf")
# => "asdf"
irb(main):009:0> s.class
# => ActiveSupport::SafeBuffer
irb(main):010:0> s.to_s.class
# => ActiveSupport::SafeBuffer
irb(main):011:0> s.to_sym.to_s
# => "asdf"
irb(main):012:0> s.to_sym.to_s.class
# => String
There's actually a method for this: String#to_str
buf = ActiveSupport::SafeBuffer.new("asdf")
str = buf.to_str #=> "asdf"
str.class #=> String
String#to_str
works exactly like String#to_s
: it returns the receiver, converting it to String if necessary. But unlike the overridden ActiveSupport::SafeBuffer#to_s
there's no ActiveSupport::SafeBuffer#to_str
so the original method is called.
Note that ActiveSupport::SafeBuffer
is a subclass of String
:
s = ActiveSupport::SafeBuffer.new("asdf")
s.is_a? String
# => true
So there's often no need to convert it at all.
interpolate it as a string:
irb(main):001:0> "#{ActiveSupport::SafeBuffer.new("asdf")}".class
=> String
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With