Class: Kiba::Extend::Utils::ExtractFractions

Inherits:
Object
  • Object
show all
Defined in:
lib/kiba/extend/utils/extract_fractions.rb

Overview

Extracts Data::ConvertibleFraction(s) from given String and returns only fractions that can be converted to decimal, in the order they will need to be replaced in the string

Instance Method Summary collapse

Constructor Details

#initialize(whole_fraction_sep: [" ", "-"]) ⇒ ExtractFractions

Returns a new instance of ExtractFractions.

Parameters:

  • whole_fraction_sep (Array(String)) (defaults to: [" ", "-"])

    List of characters that precede a fraction after a whole number, indicating that the whole number and fraction should be extracted together. If this is set to [' ', '-'] (the default), then both 1 1/2 and 1-1/2 will be extracted with 1 as the whole number and 1/2 as the fraction, and converted to 1.5. If this is set to [' '], then 1 1/2 will be extracted as described preveiously. For 1-1/2, no whole number value will be extracted. 1/2 will be extracted as the fraction, and it will be converted to ‘0.5’.



21
22
23
24
25
# File 'lib/kiba/extend/utils/extract_fractions.rb', line 21

def initialize(whole_fraction_sep: [" ", "-"])
  @whole_fraction_sep = whole_fraction_sep
  @fpattern = /(\d+\/\d+)/
  @fraction = Kiba::Extend::Data::ConvertibleFraction
end

Instance Method Details

#call(value) ⇒ Object

Parameters:

  • value (String)


28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/kiba/extend/utils/extract_fractions.rb', line 28

def call(value)
  return [] unless value.match?(fpattern)

  result = []
  scanner = StringScanner.new(value)
  scan(scanner, result)
  result.each do |fraction|
    unless fraction.convertible?
      # rubocop:todo Layout/LineLength
      warn("#{self.class.name}: Unconvertible fraction: #{value[fraction.position]}")
      # rubocop:enable Layout/LineLength
    end
  end
  result.sort.reverse
end