Escape characters appearing in an array with the `p` method without interpolation

337 views Asked by At

For overflow below, the quotes are surrounding an array.

overflow = [5,6,7]
p overflow       #=> [5, 6, 7]
p "#{overflow}"  #=> "[5, 6, 7]"

For stack below, the results are strange for the interpolated expression.

stack = 1234.to_s.chars.reverse.each_slice(3).map { |s| s.reverse.join }.reverse
p stack          #=> ["1", "234"]
p "#{stack}"     #=> "[\"1\", \"234\"]"

How does the p method show escape characters with stack, but not with overflow? Why does this occur only with interpolation as opposed to when printed without interpolation?

1

There are 1 answers

0
Yu Hao On BEST ANSWER

overflow is an array of integers while stack is an array of strings. There's nothing to escape in overflow.

Possibly you meant to make stack an array of Fxinum as well, in which case add .map(&:to_i) at the end of the method chain:

stack = 1234.to_s.chars.reverse.each_slice(3).map { |s| s.reverse.join }.reverse.map(&:to_i)

For the second question, that's how the method p works. To ge precise, the behavior is defined in String#inspect as that's the method p is using:

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