Class: RedBlocks::ComposedExpression

Inherits:
Expression show all
Defined in:
lib/red_blocks/composed_expression.rb

Instance Attribute Summary collapse

Attributes inherited from Expression

#key, #label, #score, #weight

Instance Method Summary collapse

Constructor Details

#initialize(key, operator:, operands:, weight: 1, label: nil) ⇒ ComposedExpression

Returns a new instance of ComposedExpression.



5
6
7
8
9
# File 'lib/red_blocks/composed_expression.rb', line 5

def initialize(key, operator:,  operands:, weight: 1, label: nil)
  super(key, weight: weight, label: label)
  @operator = operator
  @operands = operands
end

Instance Attribute Details

#operandsObject

Returns the value of attribute operands.



3
4
5
# File 'lib/red_blocks/composed_expression.rb', line 3

def operands
  @operands
end

#operatorObject

Returns the value of attribute operator.



3
4
5
# File 'lib/red_blocks/composed_expression.rb', line 3

def operator
  @operator
end

Instance Method Details

#to_sObject



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/red_blocks/composed_expression.rb', line 11

def to_s
  operands_str = operands
    .select { |exp| exp.is_a?(ComposedExpression) || exp.score.nil? || exp.score != 0 }
    .map { |exp| exp.to_s }
  case operator
  when :sum
    str = operands_str.join(' + ')
    str = "(#{str}) * #{weight}" if weight != 1
    str
  else
    str = "#{operator.to_s}(#{operands_str.join(', ')})"
    str = "#{str} * #{weight}" if weight != 1
    str
  end
end