Extending Array and assigning to self

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 = []
end

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

def
@content[num]
end

def <<(page_content)
@content << page_content
end

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?

On May 5, 6:21 pm, Oliver S. [email protected] wrote:

  @content = file.read.split page_delimiter

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?

Posted viahttp://www.ruby-forum.com/.

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

I’m not sure if Array#concat is the best choice here (for some
definition of best), but it’ll work.

yermej wrote:

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

I’m not sure if Array#concat is the best choice here (for some
definition of best), but it’ll work.

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’

Hi –

On Tue, 6 May 2008, yermej wrote:

def import(file, page_delimiter = ’ ')
end
class Pages < Array
def import(file, page_delimiter = ’ ')
self.clear
self.concat file.read.split.page_delimiter

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

file.read.split(page_delimiter)

just to be sure :slight_smile:

end
end

I’m not sure if Array#concat is the best choice here (for some
definition of best), but it’ll work.

In general I’d use #replace rather than #clear plus #concat.

David

In general I’d use #replace rather than #clear plus #concat.

David

Whoa! That answers the string question. Thanks :slight_smile: