'#$'.inspect contains unexpected escape character

I assumed inspecting this sequence would simply yield the characters as
is, however I’m seeing the following:

2.1.6 :001 > ‘#$’
=> “#$”
2.1.6 :002 > ‘#$’.inspect
=> “”\#$""

Can anyone explain this behavior? Is there an alternative way to
instantiate the String to yield my desired inspect result?

Matthew Ueckerman wrote in post #1177011:

I assumed inspecting this sequence would simply yield the characters as
is, however I’m seeing the following:

2.1.6 :001 > ‘#$’
=> “#$”
2.1.6 :002 > ‘#$’.inspect
=> “”\#$""

Can anyone explain this behavior?
api doc of String#inspect :

“Returns a printable version of str, surrounded by quote marks, with
special characters escaped.”

‘#’ is special character, so it must be preceding by ‘’.
Then irb print the value as string, so it surrounded all by ‘"’, and
append ‘’ if necessary.

http://apidock.com/ruby/String/inspect
f you print the resullt of inspect, you get the pure tranformation
doing by inspect :
irb> puts (’#$’.inspect)
“#$”
=> nil

the general explanation is : all literals formated by inspect must be
analysed as ruby code :
eval( x.inspect ) == x

So inspect is basic tool for serialize ruby data.

Is there an alternative way to
instantiate the String to yield my desired inspect result?

a="#$"
def a.inspect() self.to_s end
a.inspect
=> #$

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs