Data structures from C to ruby

C

Costas C.j

Hi. I am new to ruby and i know c and c++. i wonder if thre is something
similar to c pointers for ruby. Let me give an example.
I have an object foo with some methods, i have object foo2 with other
methods and foo3 object. I would like to give me a code example how i
can access from foo to foo3. Lets say that they are on a tree or graph
foo
/ \
foo2 foo3

i think the hash maybe is an option but i want something for general
purpose, example for n foos object or foo to have more than 2 children
and access from one to another.

Sorry for my English

Thank you for your Help
 
D

David Masover

Hi. I am new to ruby and i know c and c++. i wonder if thre is something
similar to c pointers for ruby.

"Similar", maybe. It depends what you want to do with them.
i think the hash maybe is an option but i want something for general
purpose, example for n foos object or foo to have more than 2 children
and access from one to another.

I'm not really sure what you're asking. Are you just trying to build a generic
tree?

All Ruby variables are handled by reference. A tree might be a bit complex --
let me see if I can clear it up with a linked list. In C, you'd do this,
right?

struct Node {
Node *prev;
Node *next;
void *data;
};

Then you could do things like this:

Node *head = malloc(sizeof(Node));
head->prev = head->next = head->data = NULL;
Node *tail = head;

void push(Node *list, void *data) {
Node *n = malloc(sizeof(Node));
n->next = NULL;
n->data = data;
n->prev = tail;
tail = n;
}

...and so on. Right?

So in Ruby, you could do it with:

class Node
attr_accessor :prev, :next, :data
end

They're just references. You can basically do exactly what you'd expect,
except you can assume stuff is nulled out by default. So, assuming one dummy
node as before, you could do stuff like:

class LinkedList
def initialize
@head = Node.new
@tail = head;
end
def push(data)
n = Node.new
n.data = data
n.prev = @tail
@tail = n
end
...
end

Exactly the same. The only difference is you don't have to free stuff.

Does that help? If not, could you please post an example of something you can
do in C, but you don't know how to do it in Ruby yet?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,061
Latest member
KetonaraKeto

Latest Threads

Top