Object and Pointers Graph Representation in Ruby

I am studying how to represent a graph in memory with Objects and Pointers in ruby and cannot find a representation of this anywhere. Can anyone point me in the right direction of how to build this ds?

1 answer

  • answered 2022-05-06 22:05 David Grayson

    There are all sorts of ways you can do this, and the best implementation will depend on the nature of the nodes and edges in your graph. One way to do it would be like this:

    # Make some objects.  Let's just use the Object class for
    # now, but they could be a custom class later.
    a = Object.new
    b = Object.new
    c = Object.new
    # Make a hash that stores edges of the graph.
    edges = {}
    edges[a] = [b, c]  # Edge from a to b and another from a to c.
    edges[b] = [c]
    edges[c] = []
    # Iterate over each object that a points to.
    edges[a].each do |obj|

    The implementation above uses a separate hash to store the edges of the graph, but you could certainly store the edges inside instance variables in the objects themselves. However, that could get messy because a.inspect would then print out the entire contents of all the objects that a points to, and then it would recursively print out the contents of all of those objects, and so on.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum