SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Problem overriding Array.to_s

    Hi,

    I'm just getting started with Ruby, and I've run into a head-scratcher. I have the following code:

    Code ruby:
    class Node < Array
      def to_s
        puts(">>")
        tokens = self.each { |token|
          puts("$ " + token.to_s)
          token.to_s
        }
        puts("<<")
        "(" + tokens.join(" ") + ")"
      end
    end
     
    n = Node.new
    n.push(1)
    n.push(2)
    m = Node.new
    m.push(3)
    m.push(4)
    n.push(m)
    puts(n.to_s)
    I would've expected this output:
    Code:
    >>
    $ 1
    $ 2
    >>
    $ 3
    $ 4
    <<
    $ (3 4)
    <<
    (1 2 (3 4))
    But instead, I get this:
    Code:
    >>
    $ 1
    $ 2
    >>
    $ 3
    $ 4
    <<
    $ (3 4)
    >>
    $ 3
    $ 4
    <<
    <<
    (1 2 3 4)
    Any ideas?

  2. #2
    SitePoint Wizard silver trophy kyberfabrikken's Avatar
    Join Date
    Jun 2004
    Location
    Copenhagen, Denmark
    Posts
    6,157
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Aha - Solved it. I have to use used map instead of each. Warms my lispy heart to find out.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •