Overload the normal behavior of an object/instance in string

Discussion in 'Ruby' started by Walle Wallen, Apr 28, 2010.

  1. Walle Wallen

    Walle Wallen Guest

    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.

    Code (Text):

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

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

    puts p
    => "#<Hejsan:0x1010fd7f8>"
     
     
    Walle Wallen, Apr 28, 2010
    #1
    1. Advertisements

  2. 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
     
    Florian Frank, Apr 28, 2010
    #2
    1. Advertisements

  3. 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.

    Try this:

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

    def to_s
    "this is a test"
    end
    end

    p =3D Test.new
    puts p
    puts "#{p}"
    puts p.inspect

    which produces:

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


    --=20
    Rick DeNatale

    Blog: http://talklikeaduck.denhaven2.com/
    Github: http://github.com/rubyredrick
    Twitter: @RickDeNatale
    WWR: http://www.workingwithrails.com/person/9021-rick-denatale
    LinkedIn: http://www.linkedin.com/in/rickdenatale
     
    Rick DeNatale, Apr 28, 2010
    #3
  4. Walle Wallen

    Walle Wallen Guest

    ah..yea.. I mistyped the example :)


    Thanks to you both. Works like charm :)
     
    Walle Wallen, Apr 28, 2010
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.