Stack Machine Interpretation

August 2, 2016 — Leave a comment
def minilang(str)
  stack = []
  register = 0
  str.split.each do |item|
    if item.to_i != 0
      register = item.to_i
    end
    case item
    when "PUSH"
      stack << register
    when "ADD"
      register = register + stack.last
      stack.pop
    when "SUB"
      register = register - (stack.last)
      stack.pop
    when "MULT"
      register = register * stack.last
      stack.pop
    when "DIV"
      register = register / stack.last
      stack.pop
    when "MOD"
      register = register % stack.last
      stack.pop
    when "POP"
      register = stack.last
      stack.pop
    when "PRINT"
      puts register
    end
  end
  nil
end

No Comments

Be the first to start the conversation!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s