(Newbie question) Subclasses

Hello all,

I just had a question with regards to subclasses. At the moment, I am
writing a simple class to extend Array for my own silly purposes.
However, I am not sure how to access the data inside the class from my
extension. Here’s an example of what I wrote(not the actual code):

class SuperDuperArray < Array
def export
self.each { |x| puts “Export: #{x}” }
end
end

Is self the best way to access the data/stuff/whatever itself? This
works fine but I don’t know if I am just being a dunce or if there is a
better(read Ruby) way of doing this.

Sorry for the stupid question.

Sven Schott

Sven Schott wrote:

Hello all,

I just had a question with regards to subclasses. At the moment, I am
writing a simple class to extend Array for my own silly purposes.
However, I am not sure how to access the data inside the class from my
extension. Here’s an example of what I wrote(not the actual code):

class SuperDuperArray < Array
def export
self.each { |x| puts “Export: #{x}” }
end
end

Is self the best way to access the data/stuff/whatever itself? This
works fine but I don’t know if I am just being a dunce or if there is a
better(read Ruby) way of doing this.

Sorry for the stupid question.

Not a stupid question at all.

When you’re writing a method of Array, you don’t have any special access
to the array elements; you just use the same methods that you normally
would. (Contrast this with the case of methods of a user-defined class,
which can access instance variables directly using “@ivar”, rather than
call accessor methods.)

The only thing I’d do differently with your code is omit the “self.”:

class SuperDuperArray < Array
def export
each { |x| puts “Export: #{x}” }
end
end