Extending Array and assigning to self

Discussion in 'Ruby' started by Oliver Saunders, May 6, 2008.

  1. I've got this class that is essentially an array with a few things
    added. Here's some of it:

    class Pages

    def initialize
    @content = []

    def import(file, page_delimiter = ' ')
    @content = file.read.split page_delimiter

    def [](num)

    def <<(page_content)
    @content << page_content


    Because I'm basically reimplementing Array I thought it might me more
    sense to inherit from Array or delegate to Array. The trouble is that I
    need to assign to @content. How do you suggest I get round this problem?
    Oliver Saunders, May 6, 2008
    1. Advertisements

  2. Oliver Saunders

    yermej Guest

    I would just use Array's own methods. E.g.:
    class Pages < Array
    def import(file, page_delimiter = ' ')
    self.concat file.read.split.page_delimiter

    I'm not sure if Array#concat is the best choice here (for some
    definition of best), but it'll work.
    yermej, May 6, 2008
    1. Advertisements

  3. Fantastic yermej. I didn't know about that concat method.

    Next point: What if I have a similar problem with strings? I'd like to
    achieve this:

    # is a string
    x = ValueChangeString.new 'foo' #=> 'foo'
    # has all the methods of string already
    x.length #=> 3
    # But also has methods that completely alter the string's value
    # whilst remaining the same object
    x.change_value! #=> 'bar'
    Oliver Saunders, May 6, 2008
  4. Hi --

    That's actually a space before page_delimiter, not a dot. Or:


    just to be sure :)
    In general I'd use #replace rather than #clear plus #concat.


    Rails training from David A. Black and Ruby Power and Light:
    INTRO TO RAILS June 9-12 Berlin
    ADVANCING WITH RAILS June 16-19 Berlin
    INTRO TO RAILS June 24-27 London (Skills Matter)
    See http://www.rubypal.com for details and updates!
    David A. Black, May 6, 2008
  5. In general I'd use #replace rather than #clear plus #concat.
    Whoa! That answers the string question. Thanks :)
    Oliver Saunders, May 6, 2008
    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.