1
+ # Problem: https://exercism.org/tracks/ruby/exercises/wordy
2
+
3
+ # Solution
4
+ class WordProblem
5
+ REPLACEMENTS = {
6
+ "plus" => "+" ,
7
+ "minus" => "-" ,
8
+ "divided by" => "/" ,
9
+ "multiplied by" => "*" ,
10
+ "what is" => ""
11
+ }
12
+ OPERATIONS = {
13
+ "+" => lambda { |a , b | a +b } ,
14
+ "-" => lambda { |a , b | a -b } ,
15
+ "/" => lambda { |a , b | a /b } ,
16
+ "*" => lambda { |a , b | a *b }
17
+ }
18
+ def initialize ( word_prob )
19
+ word_prob = word_prob . strip . gsub ( /\b (?:#{ REPLACEMENTS . keys . join ( '|' ) } )\b /i , REPLACEMENTS )
20
+ @word_prob = word_prob [ -1 ] =="?" ? word_prob [ 0 ...-1 ] : word_prob
21
+ end
22
+
23
+ def answer
24
+ words = @word_prob . split ( " " )
25
+ result = 0
26
+ i = 0
27
+ prev_num = nil
28
+ prev_op = nil
29
+ while i <words . length
30
+ if words [ i ] . match? ( /^-?\d +$/ )
31
+ unless prev_num . nil? and prev_op . nil?
32
+ result = prev_op . call ( prev_num , words [ i ] . to_i )
33
+ prev_op = nil
34
+ prev_num = result
35
+ else
36
+ prev_num = words [ i ] . to_i
37
+ end
38
+ elsif OPERATIONS . keys . include? ( words [ i ] )
39
+ prev_op = OPERATIONS [ words [ i ] ]
40
+ else
41
+ raise ArgumentError
42
+ end
43
+ i +=1
44
+ end
45
+ result
46
+ end
47
+ end
48
+
49
+ # Solution
50
+ class WordProblem
51
+ attr_reader :question
52
+ OPERATIONS = {
53
+ 'plus' => :+ ,
54
+ 'minus' => :- ,
55
+ 'divided' => :/ ,
56
+ 'multiplied' => :*
57
+ }
58
+ def initialize ( question )
59
+ @question = question
60
+ end
61
+
62
+ def answer
63
+ numbers = question . scan ( /(-?\d +)/ ) . flatten . map ( &:to_i )
64
+ operations = question . scan ( /(plus|minus|multiplied|divided)/ ) . flatten .
65
+ map { |op | OPERATIONS [ op ] }
66
+ raise ArgumentError if numbers . empty? || operations . empty?
67
+ equation = operations . unshift ( :+ ) . zip ( numbers ) . flatten . compact
68
+ equation . each_slice ( 2 ) . inject ( 0 ) do |sum , ( operation , number ) |
69
+ sum . send ( operation , number )
70
+ end
71
+ end
72
+ end
0 commit comments