Class: Termular::Context

Inherits:
Object
  • Object
show all
Defined in:
lib/termular/context.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent = nil) ⇒ Context

Returns a new instance of Context.



26
27
28
# File 'lib/termular/context.rb', line 26

def initialize(parent = nil)
  @vars, @parent = {}, parent
end

Instance Attribute Details

#parentObject

Returns the value of attribute parent.



24
25
26
# File 'lib/termular/context.rb', line 24

def parent
  @parent
end

#varsObject

Returns the value of attribute vars.



24
25
26
# File 'lib/termular/context.rb', line 24

def vars
  @vars
end

Class Method Details

.globalObject



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/termular/context.rb', line 3

def self.global
  @@global ||= begin
    ctx = Context.new
    %w( acos acosh asin asinh atan atan2 atanh cbrt cos cosh erf erfc exp
        log log10 log2 sin sinh sqrt tan tanh ).each do |m|
      ctx[m] = Math.method m
    end
    %w( PI E ).each do |c|
      ctx[c.downcase] = Math.const_get c
    end
    ctx["ln"]     = ctx["log"]
    ctx["abs"]    = ->x { x.abs }
    ctx["arg"]    = ->x { x.arg }
    ctx["ceil"]   = ->x { x.ceil }
    ctx["floor"]  = ->x { x.floor }
    ctx["int"]    = ->x { x.to_i }
    ctx["mod"]    = ->a,b { a % b }
    ctx
  end
end

Instance Method Details

#[](var) ⇒ Object



30
31
32
33
34
35
36
37
38
# File 'lib/termular/context.rb', line 30

def [](var)
  if vars.key? var
    vars[var]
  elsif parent
    parent[var]
  else
    raise "undefined variable '#{var}'"
  end        
end

#[]=(var, val) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/termular/context.rb', line 40

def []=(var, val)
  if vars.key? var
    vars[var] = val
  elsif parent and parent.has? val
    parent[var] = val
  else
    vars[var] = val
  end
end

#has?(var) ⇒ Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/termular/context.rb', line 50

def has?(var)
  vars.key?(var) or parent && parent.has?(var)
end