Ruby inspect Method Tutorial

In this section, we will learn what the inspect method is and how to use it in Ruby.

What is inspect Method in Ruby?

The `inspect` method is a type of method that can be invoked on top of any object and it will return a string representing that object in a form that is useful for debugging!

For example, when you call the `gets` method to get an input value from a user, what we get is a string value that it’s like it doesn’t have any newline character in it! But in fact, the `gets` method always returns the newline character as a result of users hitting the enter key on their keyboard.

So by default we won’t see that newline character if we simply print the string value. But using the inspect method on top of such string value, for example, will reveal that hidden string value as well.

Example: using inspect method in Ruby

puts "Please enter something"

result = gets

puts result

puts result.inspect

Output:

Please enter something

a simple string value

a simple string value

"a simple string value \n"

You can see that when we called the `inspect` method on top of the string value returned from the `gets` method, now we’re seeing that newline character as well.

Again, the use of inspect method is when we want to get a string value representing an object and this value is suitable for debugging purposes.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies