A very basic graph gem for Ruby.
Currently only unweighted, undirected graphs are supported. This means that multiple edges between nodes are ignored, although self loops are allowed.
Note that this is a very early version, and everything about this library is subject to change at any given time without notice. Expect breaking changes.
Add this line to your application's Gemfile:
gem 'simple_graph'
And then execute:
$ bundle
Or install it yourself as:
$ gem install simple_graph
Docs are built using YARD and are available at https://vesther.github.io/simple_graph/
require "simple_graph"
# Creating a new, empty graph
graph = SimpleGraph::Graph.new
# Adding nodes to the graph
# Creates a empty node containing only a autogenerated identifier
# Returns a graph-unique identifier for the newly created node
foo = graph.add_node()
# IDs can also be set manually
graph.add_node(id: "Kevin")
# Graphs can also hold arbitrary information in the 'data' hash
stuff = {
age: 21,
depression: true
}
bar = graph.add_node(id: "Igor", data: stuff)
# Edges can be created by passing the two node IDs to the connect_nodes method
graph.connect_nodes(foo, "Kevin")
# Paths between two nodes can be found by breadth-first search
paths = graph.find_paths(foo, bar)
# Retrieving info about the graph
graph.nodes # Lists all of the nodes in the graph
graph.node_count # Returns the amount of nodes in the graph
graph.node_ids # Array of node identifiers in the graph
graph.are_connected?(foo, bar) # Checks whether two nodes are connected by an Edge
graph.include?("Kevin") # Checks whether the graph includes a node with the given ID
# Graphs can be written to files in the DOT format to be used with Graphviz
# Note that the node ID will be used for labels
File.write("test.dot", graph.to_dot_string)
# Export a graph to a JSON file
File.write("output.json", graph.to_json)
# Import a graph from a JSON file
graph.load_from_json(File.read("input.json"))
Bug reports and pull requests are welcome on GitHub at https://github.com/vesther/simple_graph.
The gem is available as open source under the terms of the MIT License.