Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make ruby object attributes hidden from inspect

Tags:

ruby

So I like to use ruby inspect for debugging, however I have a class that have an array that have 6000+ elements and whenever I puts obj.inspect the array clutters the entire screen. Is there any way to make the array attribute hidden from inspect?

class Test
  def initialize
    @x = 1
    @array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
  end

  def myinspect
    # ??
  end
end

c = Test.new
puts c.inspect # <Test:0x00007f1d49e33b00 @x=1, @array=[1, 2, 3, 4, 5, 6, 7, 8, 9]>
puts c.myinspect # <Test:0x00007f1d49e33b00 @x=1>
like image 780
jvx8ss Avatar asked Oct 19 '25 09:10

jvx8ss


1 Answers

You can redefine any method in Ruby. So, in your case, you may just redefine inspect in your class Test.

Here is an example.

class Test
  alias_method :inspect_original, :inspect if ! self.method_defined?(:inspect_original)  # backup

  def inspect
    content = instance_variables.map{|i|
      sprintf("%s=%s", i, instance_variable_get(i).inspect) if i != :@array
    }.compact.join(" ")
    "<#{self.class.name}:0x#{object_id.to_s(16).rjust(16, '0')} #{content}>"
  end
end

Test.new.inspect
# => "<Test:0x00000000001fb490 @x=1>"
like image 92
Masa Sakano Avatar answered Oct 21 '25 04:10

Masa Sakano



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!