From: Paul Brannan Date: 2002-09-05T06:31:54+09:00 Subject: Re: School work (no, this isn't a homework problem) On Thu, Sep 05, 2002 at 06:11:56AM +0900, Peach wrote: > Well, I'm a Ruby Newbie, so this question should be interesting. > I somehow talked my professor at school to let me use Ruby instead of C++ > for the algorithm class. Frankly, I find using Ruby much easier than C (and > it's children). It just makes sense to me. > In a short amount of time, however, I will have a problem. Pointers will > very quickly become an integral part of our course study. To continue, I > would need to do some meaningful pointer work in Ruby. Does anyone know of > libraries to do such things, or are there other ways? If you could give some > assistance, I'd be greatly appreciated :) > I'd like to stick with Ruby, but if the answer is no I'll make do. Ruby has no pointers. However, it has references, which are just as good. If I write: a = 'foo' then a is a reference to a String object containing the text 'foo'. You can think of a reference in Ruby as a pointer with which you cannot do pointer arithmetic (in C++, you can never modify a reference; Ruby lets you reassign references, as long as their name doesn't begin with a capital letter). It's possible to write a linked list in pure Ruby, but it will be slow. For example, if I want a singly-linked list that I can only append to (not very useful), I might write: class List Node = Struct.new("Node", :next, :value) def initialize @head = nil @tail = nil end def each(node = @head, &block) return if node.nil? yield node.value each(node.next, &block) end def push(value) if @tail then @tail.next = Node.new(nil, value) @tail = @tail.next else @head = @tail = Node.new(nil, value) end end end I'll leave insertion into the beginning/middle, deletion from the list, etc. as an exercise for the reader. :) Paul