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 stringsstr1 = "Edpresso"str2 = "is"str3 = "awesome"# inspect stringsa = str1.inspectb = str2.inspectc = str3.inspect# print resultsputs aputs bputs c
Code explanation
- Lines 2–4: We create some strings and initialize them with values.
- Lines 7–9: We call the
inspectmethod on the strings that we created and store the results in the variablesa,b, andc. - Lines 12–14: We print the results to the console.