What is inspect method in Ruby: Explanation and Examples
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.
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
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
inspectto customize output.