Class: Eg::Hp35

Inherits:
Object
  • Object
show all
Defined in:
lib/eg/calculator.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeHp35

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

#rObject (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

#popObject



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