Skip to content
Advertisement

ruby Array.inspect vs. Array[element].to_s

I’m working with an array, which we’ll call books, of complex objects, which we’ll call Book. The problem is when I call puts "#{books.inspect}", ruby outputs a stream of binary (unreadable utf8 characters). However, when I call puts #{books[0].to_str}", I get a brief, pretty output that describes the book in question. Not sure if it is relevant, but Book is a subclass (we can call it’s parent class Item), and books.length=1

Ruby implies that .to_s and .inspect are synonymous, but they are clearly providing different results in practice. Does anyone know why this is happening and can you provide a suggestion for how to get the nice output I want out of the whole books collection?

Misc info:

[chk ~ ]$ ruby -v
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux]

Advertisement

Answer

class Myclass
    def to_s
        'my string representation'
    end
    def inspect
        'my inspection'
    end
end
a= [Myclass.new]
p a
puts a

outputs ::
[my inspection]
my string representation

The inspect method is called for each element inside the array. If that method is not defined you get the default class representation. You will just need to define inspect.

You could always just do :

def inspect
  self.to_s
end
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement