Class: Eg::Hp35
- Inherits:
-
Object
- Object
- Eg::Hp35
- Defined in:
- lib/eg/calculator.rb
Instance Attribute Summary collapse
-
#r ⇒ Object
readonly
Returns the value of attribute r.
Instance Method Summary collapse
-
#initialize ⇒ Hp35
constructor
A new instance of Hp35.
- #key(key) ⇒ Object
- #pop ⇒ Object
- #push(value = nil) ⇒ Object
Constructor Details
#initialize ⇒ Hp35
Returns a new instance of Hp35.
11 12 13 14 |
# File 'lib/eg/calculator.rb', line 11 def initialize @r = [0, 0, 0, 0] @s = 0 end |
Instance Attribute Details
#r ⇒ Object (readonly)
Returns the value of attribute r.
10 11 12 |
# File 'lib/eg/calculator.rb', line 10 def r @r end |
Instance Method Details
#key(key) ⇒ Object
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 |
# File 'lib/eg/calculator.rb', line 15 def key key if key.kind_of? Numeric push key.to_f else case key when 'enter' then push when '+' then push(pop() + pop()) when '-' then n = pop(); push(pop() - n) when '*' then push(pop() * pop()) when '/' then n = pop(); push(pop() / n) when 'x^y' then push(pop() ** pop()) when 'clx' then @r[0] = 0 when 'clr' then @r[0] = @r[1] = @r[2] = @r[3] = 0 when 'chs' then @r[0] = -@r[0] when 'x<>y' then @r[0], @r[1] = @r[1], @r[0] when 'r!' then @r[3] = pop() when 'sto' then @s = @r[0] when 'rcl' then push(@s) when 'sqrt' then push(Math.sqrt(pop())) when 'ln' then push(Math.log(pop())) when 'sin' then push(Math.sin(pop() / 180 * Math::PI)) when 'cos' then push(Math.cos(pop() / 180 * Math::PI)) when 'tan' then push(Math.tan(pop() / 180 * Math::PI)) else raise "Can't do key: #{key}" end end end |
#pop ⇒ Object
46 47 48 49 50 |
# File 'lib/eg/calculator.rb', line 46 def pop result = @r[0] 0.upto(2) {|i| @r[i] = @r[i + 1]} result end |
#push(value = nil) ⇒ Object
42 43 44 45 |
# File 'lib/eg/calculator.rb', line 42 def push value = nil 3.downto(1) {|i| @r[i] = @r[i - 1]} @r[0] = value unless value.nil? end |