Class: Expression

Inherits:
Object
  • Object
show all
Defined in:
lib/chebyruby/expression.rb

Overview

require_relative ‘univariate_function’

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(left, op, right) ⇒ Expression

Returns a new instance of Expression.



6
7
8
9
10
# File 'lib/chebyruby/expression.rb', line 6

def initialize(left, op, right)
  @left = left
  @op = op
  @right = right
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object



12
13
14
# File 'lib/chebyruby/expression.rb', line 12

def method_missing(method, *args)
  Expression.new(self, method, Variable.new(args[0]))
end

Instance Attribute Details

#leftObject

Returns the value of attribute left.



4
5
6
# File 'lib/chebyruby/expression.rb', line 4

def left
  @left
end

#opObject

Returns the value of attribute op.



4
5
6
# File 'lib/chebyruby/expression.rb', line 4

def op
  @op
end

#rightObject

Returns the value of attribute right.



4
5
6
# File 'lib/chebyruby/expression.rb', line 4

def right
  @right
end

Instance Method Details

#nested?Boolean

Returns:

  • (Boolean)


23
24
25
26
# File 'lib/chebyruby/expression.rb', line 23

def nested?
  {:right => (Expression === right),
   :left => (Expression === left)}
end

#to_funcObject



41
42
43
44
45
46
# File 'lib/chebyruby/expression.rb', line 41

def to_func
  if a.vars.size == 1
    blk = ->(intvar) {eval(to_s.gsub(vars[0],'intvar'))}
    UnivariateFunction.new(&blk)
  end
end

#to_sObject



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/chebyruby/expression.rb', line 28

def to_s
  if nested?[:left]
    s = "#{left.to_s} #{op}"
  else
    s = "#{left} #{op}"
  end
  case right
  when Variable then "#{s} #{right.x}".strip
  when Expression then "#{s} #{right.to_s}".strip
  else "#{s} #{right}".strip
  end
end

#varsObject



16
17
18
19
20
21
# File 'lib/chebyruby/expression.rb', line 16

def vars
  a = []
  nested?[:left] ? a << left.vars : a << left.x
  nested?[:right] ? a << right.vars : a << right.x
  (a.flatten rescue a).select{|i| String === i}.uniq
end