Question

When I was working on RubyMonk's online exercise "Ruby Primer : Ascent, 3.2 Stacks and Queues" to create a Stack class, I found that I'm not quite understanding the purpose of the self in function push.

class Stack
  def initialize(size)
    @size = size
    @stack = Array.new(@size)
    @top = -1
  end

  def pop
    if empty?
      return nil
    else
      result = @stack[@top]
      @stack[@top] = nil
      @top -= 1
      return result
    end
  end

  def push(element)
    if full? || element.nil?
      return nil
    else
      @top += 1
      @stack[@top] = element
      self
    end   
  end

  def size
    @size
  end

  def look
    @stack[@top]
  end

  private

  def full?
    @top == @size - 1
  end

  def empty?
    @top == -1
  end
end
Was it helpful?

Solution

It returns the object of class Stack itself, so you could chain method calls like this:

my_stack.push(1).push(2).push(3).size
#=> 3

Each call of push() will result in the original my_stack, so you can keep calling push().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top