読者です 読者をやめる 読者になる 読者になる

SPLIT THE NUMBER(CodeEval)

codeeval ruby

CHALLENGE DESCRIPTION:

You are given a number N and a pattern. The pattern consists of lowercase latin letters and one operation "+" or "-". The challenge is to split the number and evaluate it according to this pattern e.g. 1232 ab+cd -> a:1, b:2, c:3, d:2 -> 12+32 -> 44

INPUT SAMPLE:

Your program should accept as its first argument a path to a filename. Each line of the file is a test case, containing the number and the pattern separated by a single whitespace. E.g.

3413289830 a-bcdefghij
776 a+bc
12345 a+bcde
1232 ab+cd
90602 a+bcde

OUTPUT SAMPLE:

For each test case print out the result of pattern evaluation. E.g.

-413289827
83
2346
44
611

Constraints: N is in range [100, 1000000000]

My Code

#!/usr/bin/env ruby -w

def extract_operators(number, pattern)
  operator = pattern.scan(/[+|-]/).join
  operator_position = pattern.index(/[+|-]/)
  x = number[0...operator_position].to_i
  y = number[operator_position..-1].to_i
  [x, y, operator]
end

ARGF.each_line do |line|
  number, pattern = line.chomp.split
  x, y, operator = extract_operators(number, pattern)
  puts operator == '+' ? (x + y) : (x - y)
end