# Class: Calc::Operation

Inherits:
Object
• Object
show all
Defined in:
lib/calc/operation.rb

## Overview

A mathematical calculation from zero or more values to an output value.

## Constant Summary collapse

OperandMismatchError =

When the operation is calculated with an unexpected number of operands

`Class.new(Error)`

## Instance Attribute Summary collapse

The number of operands that the operations requires.

The symbol that signifies the Operation.

## Instance Method Summary collapse

• Calculates the operation on 0 or more operands.

• constructor

A new instance of Operation.

## Constructor Details

### #initialize(sign, command) ⇒ Operation

Returns a new instance of Operation.

Examples:

Create operation that adds 2 operands

``Operation.new('+', ->(term1, term2) { term1 + term2 })``

Parameters:

• sign (String)
• command (#call)

How to calculate the result of the operation

Raises:

• (ArgumentError)

if the command is not a lambda

 ``` 26 27 28 29 30 31 32``` ```# File 'lib/calc/operation.rb', line 26 def initialize(sign, command) raise ArgumentError, 'Command must be a lambda' unless command.lambda? @operands = command.arity @sign = sign @command = command end```

## Instance Attribute Details

Returns the number of operands that the operations requires.

Returns:

• (Integer)

the number of operands that the operations requires

 ``` 12 13 14``` ```# File 'lib/calc/operation.rb', line 12 def operands @operands end```

Returns The symbol that signifies the Calc::Operation.

Returns:

 ``` 16 17 18``` ```# File 'lib/calc/operation.rb', line 16 def sign @sign end```

## Instance Method Details

### #calculate(operand, operand) ⇒ BigDecimal

Note:

signature depends on number of operands specified to the `command` at initialization

Returns the result of the operation.

Calculates the operation on 0 or more operands

Returns:

• (BigDecimal)

the result of the operation

Raises:

• if the calculation is passed the wrong number of operands

 ``` 42 43 44 45 46``` ```# File 'lib/calc/operation.rb', line 42 def calculate(*operands) command.call(*operands) rescue ArgumentError => e raise OperandMismatchError, e.message << " to '#{sign}' operation" end```