Module: VectorNumber::Stringifying

Included in:
VectorNumber
Defined in:
lib/vector_number/stringifying.rb

Overview

Methods and options for string representation.

Constant Summary collapse

MULT_STRINGS =

Predefined symbols for multiplication to display between unit and coefficient.

Returns:

  • (Hash{Symbol => String})

Since:

  • 0.1.0

{
  asterisk: "*", # U+002A
  cross: "×", # U+00D7
  dot: "", # U+22C5
  invisible: "", # U+2062, zero-width multiplication operator
  space: " ",
  none: "",
}.freeze

Instance Method Summary collapse

Instance Method Details

#inspectString

Get a string representation of the vector.

This is similar to Complex#inspect: it returns result of #to_s in round brackets.

Examples:

VectorNumber[5, "s"].inspect # => "(5 + 1⋅'s')"

Returns:

  • (String)

See Also:

Since:

  • 0.1.0



65
66
67
68
# File 'lib/vector_number/stringifying.rb', line 65

def inspect
  # TODO: Probably make this independent of options.
  "(#{self})"
end

#to_s(mult: options[:mult]) ⇒ String

Get a string representation of the vector.

Examples:

VectorNumber[5, "s"].to_s # => "5 + 1⋅'s'"
VectorNumber["s", 5].to_s # => "1⋅'s' + 5"

with :mult argument

VectorNumber[5, "s"].to_s(mult: :asterisk) # => "5 + 1*'s'"

:mult option specified for the vector

VectorNumber[5, "s", mult: :none].to_s # => "5 + 1's'"

Parameters:

  • mult (Symbol, String) (defaults to: options[:mult])

    text to use between coefficient and unit, can be one of the keys in MULT_STRINGS or an arbitrary string

Returns:

  • (String)

Raises:

  • (ArgumentError)

    if mult is not a String and is not in MULT_STRINGS‘s keys

Since:

  • 0.1.0



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/vector_number/stringifying.rb', line 38

def to_s(mult: options[:mult])
  return "0" if zero?

  result = +""
  each_with_index do |(unit, coefficient), index|
    if index.zero?
      result << "-" if coefficient.negative?
    else
      result << (coefficient.positive? ? " + " : " - ")
    end
    result << value_to_s(unit, coefficient.abs, mult: mult)
  end
  result
end