1

Basically, I want to have my own array-like class with my own methods.

I would like to initialize it by passing an arguement of the length of an array, and it should instantiate a new array with given length and filled with zeros. So I've written something like this:

class Foo < Array
  def initialize(length)
    Array.new(length, 0)
  end
end

But when I test this out in IRB i get this:

a = Foo.new(5)
=> [] 

I also tried using for-loop to fill this array with zeros n-times, but to no avail.

What am I doing wrong?

2 Answers 2

4

Because you inherited from Array you can do this:

class Foo < Array
  def initialize(length)
    super(length, 0)
  end
end

Note that super calls the original initialize method on Array.

Foo.new(5)
#=> [0, 0, 0, 0, 0]
Sign up to request clarification or add additional context in comments.

Comments

3

The implementation of Class#new looks a bit like this:

class Class
  def new(*args, &block)
    obj = allocate
    obj.initialize(*args, &block)
    obj
  end
end

[Note: in reality, initialize is private, so it needs to be invoked reflectively, but you get the idea.]

IOW: the return value of initialize is completely ignored.

If you want to change the return value of new, you need to override new. (Kinda obvious, don't you think?) But in this case, it is also possible (and in general a good idea anyway) to simply delegate to the superclass's initialize, as in @spickermann's answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.