I've created a class called SpecialArray and I'd like to customize what sort of output irb shows. Currently, when I create a new instance of the class, irb returns the entire object. This is what I currently see:

1.9.3p194 :022 > SpecialArray.new([1,2,0,6,2,11]) 
=> #<UniqueArray:0x007ff05b026ec8 @input=[1, 2, 0, 6, 2, 11], @output=[1, 2, 0, 6, 11]>

But I'd like to only show what I've defined as output. In other words, I'd like to see this.

1.9.3p194 :022 > SpecialArray.new([1,2,0,6,2,11]) 
=> [1, 2, 0, 6, 11]

What do I need to do specify that irb should only display the output?

SOLUTION:

This is the method that I ended up creating.

def inspect
  output.inspect
end
有帮助吗?

解决方案

IRB calls Object#inspect method to get string representation of your object. All you need is to override this method like that:

class Foo
  def inspect
    "foo:#{object_id}"
  end
end

Then in the IRB you'll get:

>> Foo.new
=> foo:70250368430260 

In your particular case just make SpecialArray#inspect return string representation of the underlying array, e.g.:

SpecialArray
  def inspect
    @output.inspect
  end
end
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top