Cute Little Solution

I’m learning Ruby and one small exercise was meant to calculate the sum for simple sentences like this: “eight plus 5 plus five minus three plus 1 minus 4” and output an answer. Numbers can be either numeric or written out. Every set of numbers is separated by either “plus” or “minus.” I’m sure there are many ways to complete this problem. I came up with the cute little solution below.

NUMBERS = {
  "zero"  => 0,
  "one"   => 1,
  "two"   => 2,
  "thrid" => 3,
  "four"  => 4,
  "five"  => 5,
  "six"   => 6,
  "seven" => 7,
  "eight" => 8,
  "nine"  => 9
}

OPERATIONS = ['plus', 'minus']

def is_int?(int)
  int.to_i.to_s == int
end

def translate_number(number)
  return number.to_i if is_int?(number)
  NUMBERS[number]
end

def compute(operation, number)
  case operation
  when 'plus' then number
  when 'minus' then -number
  end
end

def computer(expression)
  express_array = expression.split
  total = translate_number(express_array.shift)
  operation = nil
  express_array.each do |element|
    if OPERATIONS.include?(element)
      operation = element
      next
    end
    number = translate_number(element)
    total += compute(operation, number)
  end
  total
end

p computer("two plus two minus one plus 8 plus five minus 3")
Advertisements

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