简体   繁体   中英

irb's behavior for escaping double quotes

Inside the irb:

"\'" 

returns "'" , however

"\""

returns "\\"" , ie, it's the same as the input, without escaping the double quote. Using it with puts works as expected, but why does it not work when it is tried in this manner?

irb is working perfectly. You can't expect it to output """ .

By definition:

an escape character is a character which invokes an alternative interpretation on subsequent characters in a character sequence.

In your expected output """ clearly middle " has a different interpretation. Hence its getting escaped.

To make things clearer:

"\""
#=> "\""
puts "\""
# "

IRB uses Object#inspect by default after a statement execution to display the result of statement.

In case of String#inspect , the documentation says

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

irb(main):001:0> "\""
=> "\""
irb(main):002:0> '"'
=> "\""

When starting IRB, you could pass --noinspect option, in which case, irb will use to_s to print result.

For example, if we had a class:

class Test
    def to_s
        "#{self.class} instance"
    end
end

Default IRB:

irb(main):003:0> Test.new
=> #<Test:0x00000002ad7fa8>

With irb --noinspect

irb(main):002:0> Test.new
=> Test instance
irb(main):003:0> "\""
=> "
irb(main):004:0> '"'
=> "
irb(main):005:0>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM