Question

I do the following in irb and have also tried out the same code in pry

class Number < Struct.new(:value)
end

class Number
  def to_s
    value.to_s
  end

  def inspect
    "<<#{self}>>"
  end
end

Now, if i do Number.new(2), it correctly returns <<2>> in irb, but in pry it incorrectly returns #<struct Number value=2> . Why is this so ?

Thank You

Was it helpful?

Solution

I'm not very familiar with pry (I've never used it until just now), but the obvious answer to your question is: because pry isn't calling inspect on your object. You can manually call it, and it works as expected:

Number.new(2).inspect
# => "<<2>>"

My question was: why isn't pry calling inspect, and what's it doing instead? Looking at the code, it looks like it calls pretty_inspect instead. There may be a smarter workaround, but the simplest thing that comes to mind for me is to just alias pretty_inspect to inspect for Number:

class Number
  alias_method :pretty_inspect, :inspect
end

Number.new(2)
# => <<2>>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top