-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfluentCalculator.rb
More file actions
47 lines (36 loc) · 1.09 KB
/
fluentCalculator.rb
File metadata and controls
47 lines (36 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
=begin
Source: Codewars
Difficulty: 4 kyu
Title: Fluent Calculator
Description:
The goal is to implement simple calculator which uses fluent syntax:
Calc.new.one.plus.two # Should return 3
Calc.new.five.minus.six # Should return -1
Calc.new.seven.times.two # Should return 14
Calc.new.nine.divided_by.three # Should return 3
There are only four operations that are supported (plus, minus, times, divided_by)
and 10 digits (zero, one, two, three, four, five, six, seven, eight, nine).
Each calculation consists of one operation only.
=end
class Calc
def initialize
@first, @op, @result = nil
end
[:zero, :one, :two, :three, :four,
:five, :six, :seven, :eight, :nine].each_with_index do |method, value|
define_method("#{method}") do
if @first
@result = @first.send(@op, value)
else
@first = value
self
end
end
end
{:plus => :+, :minus => :-, :times => :*, :divided_by => :/ }.each do |key, value|
define_method("#{key}") do
@op = value
self
end
end
end