tags:

views:

170

answers:

5

This is just a hypothetical question, if you wouldn't have the Array and the Hash class, would there be any way of implementing an Array class in pure Ruby? How?

+3  A: 

You could use a linked list, which would be horrendously inefficient, but possible. You could also use a binary tree (see above comments).

I guess, my point is: you couldn't get a decent array without lower level language support. The basic structure that I assume is used in the Ruby array is a C array (though I could be wrong). With such a fundamental type, lower level support will be crucial for anywhere decent performance.

Peter
Haven't thought about that. Interesting :)
Geo
+2  A: 

You can implement [] in any object. For example:

def [](index)
    proxy_object.send(index.to_sym)
end
Sam C
I know that, I was referring to an array per-se.
Geo
A: 

I guess that's not possible without low level programming features, specially pointers...

khelll
pointers, in particular, are easily reproduced in ruby, even w/o the array - a pointer is just a reference.
Peter
How would u implement a linked list for example?
khelll
A linked list? That's nothing. `class LinkedListItem; attr_accessor :head, :tail; end`.
Chuck
Ah sorry, still thinking in memory wise! sorry again!!!
khelll
A: 

Sure you can. Ruby is a Turing-complete language. You can implement everything that you can implement in any language in Ruby.

Jörg W Mittag
+3  A: 

Yes we can!

class MyArray
  include Enumerable

  def initialize
    @size = 0
  end

  def <<(val)
    instance_variable_set("@a#{@size}".to_sym, val)
    @size += 1
  end

  def [](n)
    instance_variable_get("@a#{n}")
  end

  def length
    @size
  end

  def each
    0.upto(@size - 1) { |n| yield self[n] }
  end
end

a = MyArray.new
a << 1
a << 2
p a.to_a     #=> [1,2]

This works by creating instance variables @a0, @a1, etc. on the object to represent array indices 0, 1, etc. It has constant time length and index operations. The rest of the operations (remove, etc.) are a bit more effort to implement, but it's absolutely possible.

Note that the constant time property for the index operation depends on the underlying Ruby runtime using an appropriate data structure for instance variables.

Grandpa
I think this the most ruby-esque solution.
Geo