0
0
RubyConceptBeginner · 3 min read

What is inspect method in Ruby: Explanation and Examples

In Ruby, the inspect method returns a string that shows a human-readable representation of an object, often used for debugging. It helps you see the internal state or contents of objects in a clear format.
⚙️

How It Works

The inspect method in Ruby is like looking at a snapshot of an object that shows its details in a way that's easy to understand. Imagine you have a box with things inside, and inspect tells you what's inside the box without opening it physically.

When you call inspect on an object, Ruby returns a string that describes the object’s type and its contents or attributes. This is especially useful when you want to quickly check what data an object holds during your program's execution.

💻

Example

This example shows how inspect works on different objects like strings, arrays, and custom objects.

ruby
name = "Alice"
puts name.inspect

numbers = [1, 2, 3]
puts numbers.inspect

class Person
  def initialize(name, age)
    @name = name
    @age = age
  end
end

person = Person.new("Bob", 30)
puts person.inspect
Output
"Alice" [1, 2, 3] #<Person:0x000055b8c8a3b1b8>
🎯

When to Use

You use inspect mainly when you want to debug your code or understand what an object contains at a certain point. It is very helpful in logging or printing objects during development to see their current state.

For example, if you have a complex data structure like a hash or an array, inspect shows you all the elements inside clearly. It’s also useful when you want to customize how your own objects display their information by overriding the inspect method.

Key Points

  • inspect returns a string showing an object's details.
  • It is mainly used for debugging and logging.
  • Works on all Ruby objects, including custom ones.
  • You can override inspect to customize output.

Key Takeaways

The inspect method gives a readable string showing an object's contents.
Use inspect to debug and understand objects during development.
All Ruby objects have an inspect method by default.
You can customize inspect output by defining it in your classes.