As I go through my learning in Ruby I find myself constantly writing puts, p and print to output some result in the console window. However I found this distracting when reading the code as it is the first thing on the line and not what I really want to focus on. What I need is something similar to the Dump() extension method in LINQPad. I therefore came up with the code snippet below to try to reproduce the functionality.
class Object
def dump
if self.respond_to?("to_str")
puts self.to_str()
else
puts self
end
end
end
class Person
end
class Employee < Person
def to_str
"Employee ID: #{self.object_id}"
end
end
person = Person.new
person.dump()
employee = Employee.new
employee.dump()
Output:
#<Person:0x817140>
Employee ID: 4241496
Note that I might be off the mark here and there might be better ways to do this in Ruby but I’m just starting!
Update
Using a module to accomplish the above would make more sense. So here is the revised version.
dump.rb
module Dumpable
def dump
if self.respond_to?("to_str")
puts self.to_str()
else
puts self
end
end
end
test.rb
require "./dump.rb"
include Dumpable
class Person
end
class Employee < Person
def to_str
"Employee ID: #{self.object_id}"
end
end
person = Person.new
person.dump()
employee = Employee.new
employee.dump()
Update 2
Just realised that we can simply override to_s (to string) method instead of implementing a different method.
dump.rb
module Dumpable
def dump
puts self
end
end
test.rb
require "./dump.rb"
include Dumpable
class Person
end
class Employee < Person
def to_s
"Employee ID: #{self.object_id}"
end
end
person = Person.new
person.dump()
employee = Employee.new
employee.dump()