How to make a similar ruby ​​output to the screen using obj.inspect in the console for this object:

ruby -e "p 'hello world!'" 

Or obj.inspect not intended for the console?

  • p 'hello world!' This is an abbreviation for puts 'hello world!'. inspect. Both methods can be used for console output. While it is not very clear what causes the difficulty? - cheops
  • Without .inspect also works. Then why specify it? - Ilnyr
  • Then, with .inspect and without it, the output is different. Both in content and in meaning. - D-side

1 answer 1

The documentation for Kernel.p clearly states:

For each object, obj.inspect followed directly by the program's standard output.


For each object, displays obj.inspect and then a line obj.inspect in standard output.

Object#inspect does not deal with output at all:

Returns a string containing a human-readable representation of obj .


Returns a string containing the human-readable representation of obj .

... and at String , the inspect method inherited from Object is redefined :

Returns is a printable version of the str.


Returns a printable version of str , surrounded by quotes and with escaped special characters.

... thus obtaining the literal of a given string, suitable for insertion into Ruby-code. If you look at the contents of strings displayed using puts :

  • source line contains hello world
  • The .inspect line contains "hello world"
  • the .inspect.inspect line contains "\"hello world\"" because there were double quotes in the inspected line, in this form they were escaped

See the pattern?