Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Ruby have containers like stacks, queues, linked-lists, maps, or sets?

Tags:

ruby

I checked several Ruby tutorials online and they seemed to use array for everything. So how could I implement the following data structures in Ruby?

  • Stacks
  • Queues
  • Linked lists
  • Maps
  • Sets
like image 293
Chan Avatar asked Feb 15 '11 16:02

Chan


People also ask

Does Ruby have a stack?

Understanding Stacks in Ruby What is a stack in Ruby? A stack is a data structure which you can use as a “to-do” list. You keep taking elements from the stack & processing them until the stack is empty.

What is a data structure in Ruby?

A data structure is a specific way to organize & access data. Examples include: Arrays. Binary trees. Hashes.

Does stack use array or linked list?

Stack: Linked list: As a singly-linked list with a head pointer. Array: As a dynamic array.


2 Answers

(Moved from Comment)

Well, an array can be a stack or queue by limiting yourself to stack or queue methods (push, pop, shift, unshift). Using push / pop gives LIFO(last in first out) behavior (stack), while using push / shift or unshift / pop gives FIFO behavior (queue).

Maps are hashes, and a Set class already exists.

You could implement a linked list using classes, but arrays will give linked-list like behavior using the standard array methods.

like image 50
James Avatar answered Sep 17 '22 21:09

James


I guess most of it is covered in above answers but just for summing it up for a better explanation:

Stack:

stack = [] stack << 2 # push 2 => stack = [2] stack << 3 # push 3 => stack = [2, 3] stack.pop  # pop => 3, stack = [2] 

Queue:

# we have a Queue class queue = Queue.new queue << 2 # push 2 => queue = [2] queue << 3 # push 3 => queue = [2, 3] (just a representation, it will be an object though) queue.pop # pop 2 

Linked List:

# A very simple representation class Node   attr_accessor :value, :next_node    def initialize(value, next_node=nil)     @value = value     @next_node = next_node   end end  class LinkedList    def initialize(value)     @head = Node.new(value)   end    def add(value)     current = @head     while !current.next_node.nil?       current = current.next_node     end     current.next_node = Node.new(value)   end end  ll = LinkedList.new ll.add(10) ll.add(20) 

Maps:

# Hash incase of ruby a = {} (or a = Hash.new) a['one'] = 1 # a = {"one"=>1} a['two'] = 2 # a = {"one"=>1, "two"=>2} 

Set:

# we have a Set class require 'set' s = Set.new         # <Set: {}> s.add(1)            # <Set: {1}> s.add(2)            # <Set: {1, 2}> s.add(1)            # <Set: {1, 2}> s.instance_of?(Set) # true 
like image 45
divyum Avatar answered Sep 20 '22 21:09

divyum