tags:

views:

772

answers:

3

In Ruby, is there the equivalent of the __str__() method that you can define on Python classes?

+2  A: 

On the core classes it is typically 'inspect'.

Eg:

irb(main):001:0> puts "array is: #{[1,2,3].inspect}"
array is: [1, 2, 3]
=> nil
irb(main):002:0> puts "array is: #{[1,2,3]}"
array is: 123
=> nil
irb(main):003:0>
Kyle Burton
+7  A: 

You could use to_s.

http://briancarper.net/2006/09/26/ruby-to_s-vs-to_str/

Geoffrey Chetwood
`to_s` is the correct equivalent to `__str__`
thenduks
+5  A: 

FWIW, inspect is probably more like __repr__() than __str__()

from the library reference...

repr( self)

Called by the repr() built-in function and by string conversions (reverse quotes) to compute the ``official'' string representation of an object. If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form "<...some useful description...>" should be returned. The return value must be a string object. If a class defines __repr__() but not __str__(), then __repr__() is also used when an ``informal'' string representation of instances of that class is required.

mmaibaum