Overload the normal behavior of an object/instance in string

Long story short. I’m trying to overload the normal behavior of an
object/instance in a string. Instead of replying “Test:0x101121db0” I
would like it too return a specific string, or something similar. I have
tried to overload inspect, and it seems to work pretty well, except when
using the object with puts or in a string “#{p}”.

My english ain’t good, but I hope you understand the principle of what I
am trying to achieve.

class Test
  def inspect
     puts "this is a test"
  end
end

p = Test.new
this is a test
>> p
this is a test

puts p
#<Test:0x101121db0>

>> "#{p}"
=> "#<Hejsan:0x1010fd7f8>"

On 28/04/2010 19:03, Walle W. wrote:

class Test
this is a test

puts p
#Test:0x101121db0

“#{p}”

=> “#Hejsan:0x1010fd7f8
[/code]

You should return strings from these methods:

class Test
def inspect
“this is a test” # return the string, don’t output it
end

def to_s
“this is another test”
end
end

Then ruby can call Test#inspect or Test#to_s as it desires:

p Test.new # outputs: this is a test
puts Test.new # outputs: this is another test

On Wed, Apr 28, 2010 at 1:03 PM, Walle W. [email protected]
wrote:

Long story short. I’m trying to overload the normal behavior of an
object/instance in a string. Instead of replying “Test:0x101121db0” I
would like it too return a specific string, or something similar. I have
tried to overload inspect, and it seems to work pretty well, except when
using the object with puts or in a string “#{p}”.

My english ain’t good, but I hope you understand the principle of what I
am trying to achieve.

There are two different methods which Ruby uses to get a printstring
from an object, both of which should return a String.

inspect produces a ‘programmer friendly’ printstring in general, while
to_s produces a ‘user friendly’ string.

There’s a Kernel method p which is roughly equvalent to:

def p(arg)
puts arg.inspect
end

puts just uses to_s to convert non-strings to strings.

And irb displays the the value of inspect after evaluating an
expression.

[code]
class Test
def inspect
puts “this is a test”
end

This should simply return the string, you don’t always want to puts
the result, and puts will cause the result to be nil, not the string.

“#{p}”
=> “#Hejsan:0x1010fd7f8
[/code]

Try this:

class Test
def inspect
“this is a test inspection”
end

def to_s
“this is a test”
end
end

p = Test.new
puts p
puts “#{p}”
puts p.inspect

which produces:

this is a test
this is a test
this is a test inspection


Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Github: rubyredrick (Rick DeNatale) · GitHub
Twitter: @RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

Florian F. wrote:

On 28/04/2010 19:03, Walle W. wrote:
You should return strings from these methods:
ah…yea… I mistyped the example :slight_smile:

Thanks to you both. Works like charm :slight_smile: