What is the string.inspect method in Ruby?

Overview

In Ruby, the inspect string method is used to return a printable version of a string that is surrounded by quotes. If there are any special characters present in the string, they will be escaped.

Syntax

str.inspect

Parameters

  • str: The string that we want to inspect.

Return value

This method returns a string that is surrounded by quotation marks.

Code example

# create strings
str1 = "Edpresso"
str2 = "is"
str3 = "awesome"
# inspect strings
a = str1.inspect
b = str2.inspect
c = str3.inspect
# print results
puts a
puts b
puts c

Code explanation

  • Lines 2–4: We create some strings and initialize them with values.
  • Lines 7–9: We call the inspect method on the strings that we created and store the results in the variables a, b, and c.
  • Lines 12–14: We print the results to the console.

Free Resources