Ben Downey
Ben Downey

Reputation: 2665

Customizing class to elicit certain irb behavior

I've created a class called SpecialArray and I'd like to customize what sort of output irb shows. When I create an instance variable, test_array, and generate an array using SpecialArray, and I type "test_array" into irb, I get this:

1.9.3p194 :051 > test_array
=> [1, 2, 0, 6, 11]

And when I use "puts", irb just returns the object, like so:

1.9.3p194 :054 > puts test_array
#<SpecialArray:0x007ff05d0b4960>        

But I'd like to have irb behave more like the first example, where I only typed "test_array: (i.e. I'd like to return the array in a single line). I tried overriding the default puts method with my own, but without much success. Any suggestions on how to do this?

Upvotes: 0

Views: 52

Answers (1)

Jason Waldrip
Jason Waldrip

Reputation: 5148

Test_array is an object and when calling puts directly on the object will generally return you the instance.

You should be using the following in your puts method:

puts test_array.to_s

Upvotes: 0

Related Questions