Skip to content

Feat: Numbers to strings that generate coherent speech #213

@Wessel-Boers

Description

@Wessel-Boers

I wanted to use this gem to change numbers that represent years to strings that can be used by AI's to generate speech. However, at least for Dutch:

platform(dev):016> I18n.with_locale(:nl) { 1910.to_words }
=> "duizend negenhonderdtien"

Is not how we pronounce years. Instead it would be: "negentienhonderd tien". I wrote a quick Module extension that could be added for just Dutch or also other languages for which this is a similar problem. I'm not sure how to add this as a PR, since I'm not familiar with the conventions and how this would become accessible as an option, but perhaps this is useful for others as well.

class NumberConverter
  def self.to_words(number, locale: I18n.locale)
    new(number, locale).to_words
  end

  def initialize(number, locale)
    @number = number
    @locale = locale
  end

  def to_words
    return @number.to_words unless year_like?

    I18n.with_locale(@locale) do
      century = @number / 100
      remainder = @number % 100

      if remainder.zero?
        "#{century.to_words}honderd"
      else
        "#{century.to_words}honderd #{remainder.to_words}"
      end
    end
  end

  private

  def year_like?
    @number >= 1000 && @number < 3000
  end
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions