i override the to_s method to get pretty output when i use puts but at the same time i seem to loose my ability to inspect the object. Is there a way to get the normal output of inspect while overriding to_s ?
class Person
attr_accessor :first, :last, :birthdate
def initialize(first=nil, last=nil, birthdate=nil)
@first, @last, @birthdate = first, last, birthdate
end
def age
if birthdate
Time.now.year-birthdate
else
0
end
end
def to_s
"#{@first} #{@last} (#{age})"
end
end
me = Person.new("Peter", "Marien", 1962)
p me >>Peter Marien (50)
p me.inspect >>"Peter Marien (50)"
#Need #<Person:0x1ec2550 @first="Peter", @last="Marien", @birthdate=1962>
Ruby documentation clearly states, that by default
inspectusesto_sas its output.If you don’t need the address of the object, you could provide your own inspect, to have almost the same behavior:
But you could also install a gem called
awesome_printthat will give very nice output.First in console:
then in irb or your script:
There is also a built-in
pplibrary, which have similar purpose. Still it is not immune (at least in Ruby 1.9.2-p290) to overriding ofto_s.A quick example of
pp: