|
| 1 | +Returns a printable version of +self+, enclosed in double-quotes: |
| 2 | + |
| 3 | + 'hello'.dump # => "\"hello\"" |
| 4 | + |
| 5 | +Certain special characters are rendered with escapes: |
| 6 | + |
| 7 | + '"'.dump # => "\"\\\"\"" |
| 8 | + '\\'.dump # => "\"\\\\\"" |
| 9 | + |
| 10 | +Non-printing characters are rendered with escapes: |
| 11 | + |
| 12 | + s = '' |
| 13 | + s << 7 # Alarm (bell). |
| 14 | + s << 8 # Back space. |
| 15 | + s << 9 # Horizontal tab. |
| 16 | + s << 10 # Line feed. |
| 17 | + s << 11 # Vertical tab. |
| 18 | + s << 12 # Form feed. |
| 19 | + s << 13 # Carriage return. |
| 20 | + s # => "\a\b\t\n\v\f\r" |
| 21 | + s.dump # => "\"\\a\\b\\t\\n\\v\\f\\r\"" |
| 22 | + |
| 23 | +If +self+ is encoded in UTF-8 and contains Unicode characters, renders Unicode |
| 24 | +characters in Unicode escape sequence: |
| 25 | + |
| 26 | + 'тест'.dump # => "\"\\u0442\\u0435\\u0441\\u0442\"" |
| 27 | + 'こんにちは'.dump # => "\"\\u3053\\u3093\\u306B\\u3061\\u306F\"" |
| 28 | + |
| 29 | +If the encoding of +self+ is not ASCII-compatible (i.e., +self.encoding.ascii_compatible?+ |
| 30 | +returns +false+), renders all ASCII-compatible bytes as ASCII characters and all |
| 31 | +other bytes as hexadecimal. Appends <tt>.dup.force_encoding(\"encoding\")</tt>, where |
| 32 | +<tt><encoding></tt> is +self.encoding.name+: |
| 33 | + |
| 34 | + s = 'hello' |
| 35 | + s.encoding # => #<Encoding:UTF-8> |
| 36 | + s.dump # => "\"hello\"" |
| 37 | + s.encode('utf-16').dump # => "\"\\xFE\\xFF\\x00h\\x00e\\x00l\\x00l\\x00o\".dup.force_encoding(\"UTF-16\")" |
| 38 | + s.encode('utf-16le').dump # => "\"h\\x00e\\x00l\\x00l\\x00o\\x00\".dup.force_encoding(\"UTF-16LE\")" |
| 39 | + |
| 40 | + s = 'тест' |
| 41 | + s.encoding # => #<Encoding:UTF-8> |
| 42 | + s.dump # => "\"\\u0442\\u0435\\u0441\\u0442\"" |
| 43 | + s.encode('utf-16').dump # => "\"\\xFE\\xFF\\x04B\\x045\\x04A\\x04B\".dup.force_encoding(\"UTF-16\")" |
| 44 | + s.encode('utf-16le').dump # => "\"B\\x045\\x04A\\x04B\\x04\".dup.force_encoding(\"UTF-16LE\")" |
| 45 | + |
| 46 | + s = 'こんにちは' |
| 47 | + s.encoding # => #<Encoding:UTF-8> |
| 48 | + s.dump # => "\"\\u3053\\u3093\\u306B\\u3061\\u306F\"" |
| 49 | + s.encode('utf-16').dump # => "\"\\xFE\\xFF0S0\\x930k0a0o\".dup.force_encoding(\"UTF-16\")" |
| 50 | + s.encode('utf-16le').dump # => "\"S0\\x930k0a0o0\".dup.force_encoding(\"UTF-16LE\")" |
| 51 | + |
| 52 | +Related: see {Converting to New String}[rdoc-ref:String@Converting+to+New+String]. |
0 commit comments