Exercism v3 launches on Sept 1st 2021. Learn more! ๐Ÿš€๐Ÿš€๐Ÿš€
Avatar of rootulp

rootulp's solution

to Say in the Ruby Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Note:

This solution was written on an old version of Exercism. The tests below might not correspond to the solution code, and the exercise may have changed since this code was written.

Given a number from 0 to 999,999,999,999, spell out that number in English.

Step 1

Handle the basic case of 0 through 99.

If the input to the program is 22, then the output should be 'twenty-two'.

Your program should complain loudly if given a number outside the blessed range.

Some good test cases for this program are:

  • 0
  • 14
  • 50
  • 98
  • -1
  • 100

Extension

If you're on a Mac, shell out to Mac OS X's say program to talk out loud.

Step 2

Implement breaking a number up into chunks of thousands.

So 1234567890 should yield a list like 1, 234, 567, and 890, while the far simpler 1000 should yield just 1 and 0.

The program must also report any values that are out of range.

Step 3

Now handle inserting the appropriate scale word between those chunks.

So 1234567890 should yield '1 billion 234 million 567 thousand 890'

The program must also report any values that are out of range. It's fine to stop at "trillion".

Step 4

Put it all together to get nothing but plain English.

12345 should give twelve thousand three hundred forty-five.

The program must also report any values that are out of range.

Extensions

Use and (correctly) when spelling out the number in English:

  • 14 becomes "fourteen".
  • 100 becomes "one hundred".
  • 120 becomes "one hundred and twenty".
  • 1002 becomes "one thousand and two".
  • 1323 becomes "one thousand three hundred and twenty-three".

For installation and learning resources, refer to the exercism help page.

For running the tests provided, you will need the Minitest gem. Open a terminal window and run the following command to install minitest:

gem install minitest

If you would like color output, you can require 'minitest/pride' in the test file, or note the alternative instruction, below, for running the test file.

Run the tests from the exercise directory using the following command:

ruby say_test.rb

To include color from the command line:

ruby -r minitest/pride say_test.rb

Source

A variation on JavaRanch CattleDrive, exercise 4a http://www.javaranch.com/say.jsp

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

say_test.rb

require 'minitest/autorun'
require_relative 'say'

# Common test data version: 1.0.0 be403e1
class SayTest < Minitest::Test
  def test_zero
    # skip
    question = 0
    assert_equal('zero', Say.new(question).in_english)
  end

  def test_one
    skip
    question = 1
    assert_equal('one', Say.new(question).in_english)
  end

  def test_fourteen
    skip
    question = 14
    assert_equal('fourteen', Say.new(question).in_english)
  end

  def test_twenty
    skip
    question = 20
    assert_equal('twenty', Say.new(question).in_english)
  end

  def test_twenty_two
    skip
    question = 22
    assert_equal('twenty-two', Say.new(question).in_english)
  end

  def test_one_hundred
    skip
    question = 100
    assert_equal('one hundred', Say.new(question).in_english)
  end

  def test_one_hundred_twenty_three
    skip
    question = 123
    assert_equal('one hundred twenty-three', Say.new(question).in_english)
  end

  def test_one_thousand
    skip
    question = 1_000
    assert_equal('one thousand', Say.new(question).in_english)
  end

  def test_one_thousand_two_hundred_thirty_four
    skip
    question = 1_234
    assert_equal('one thousand two hundred thirty-four', Say.new(question).in_english)
  end

  def test_one_million
    skip
    question = 1_000_000
    assert_equal('one million', Say.new(question).in_english)
  end

  def test_one_million_two_thousand_three_hundred_forty_five
    skip
    question = 1_002_345
    assert_equal('one million two thousand three hundred forty-five', Say.new(question).in_english)
  end

  def test_one_billion
    skip
    question = 1_000_000_000
    assert_equal('one billion', Say.new(question).in_english)
  end

  def test_a_big_number
    skip
    question = 987_654_321_123
    assert_equal('nine hundred eighty-seven billion six hundred fifty-four million three hundred twenty-one thousand one hundred twenty-three', Say.new(question).in_english)
  end

  def test_numbers_below_zero_are_out_of_range
    skip
    question = -1
    assert_raises ArgumentError do
      Say.new(question).in_english
    end
  end

  def test_numbers_above_999999999999_are_out_of_range
    skip
    question = 1_000_000_000_000
    assert_raises ArgumentError do
      Say.new(question).in_english
    end
  end

  # Problems in exercism evolve over time, as we find better ways to ask
  # questions.
  # The version number refers to the version of the problem you solved,
  # not your solution.
  #
  # Define a constant named VERSION inside of the top level BookKeeping
  # module, which may be placed near the end of your file.
  #
  # In your file, it will look like this:
  #
  # module BookKeeping
  #   VERSION = 1 # Where the version number matches the one in the test.
  # end
  #
  # If you are curious, read more about constants on RubyDoc:
  # http://ruby-doc.org/docs/ruby-doc-bundle/UsersGuide/rg/constants.html

  def test_bookkeeping
    skip
    assert_equal 1, BookKeeping::VERSION
  end
end
# Say
class Say
  UNITS = {
    1 => 'thousand',
    2 => 'million',
    3 => 'billion'
  }.freeze
  TENS = {
    90 => 'ninety',
    80 => 'eighty',
    70 => 'seventy',
    60 => 'sixty',
    50 => 'fifty',
    40 => 'forty',
    30 => 'thirty',
    20 => 'twenty'
  }.freeze
  TEENS = {
    19 => 'nineteen',
    17 => 'seventeen',
    16 => 'sixteen',
    15 => 'fifteen',
    14 => 'fourteen',
    13 => 'thirteen',
    12 => 'twelve',
    11 => 'eleven',
    10 => 'ten'
  }.freeze
  DIGITS = {
    9 => 'nine',
    8 => 'eight',
    7 => 'seven',
    6 => 'six',
    5 => 'five',
    4 => 'four',
    3 => 'three',
    2 => 'two',
    1 => 'one'
  }.freeze

  ACCEPTED_RANGE = 0...1_000_000_000_000

  attr_reader :number
  def initialize(number)
    raise ArgumentError unless ACCEPTED_RANGE.include?(number)
    @number = number
  end

  def in_english
    number_to_words(number)
  end

  private

  def number_to_words(number)
    return 'zero' if number == 0
    result = ''
    chunks = chunkify(number)
    chunks.each_with_index do |chunk, index|
      val = chunk_for(chunk)
      units = UNITS[index]
      result.prepend("#{val} #{units} ") if val
    end
    result.strip
  end

  def chunkify(number)
    chunks = []
    while number > 0
      number, chunk = number.divmod(1000)
      chunks << chunk
    end
    chunks
  end

  def chunk_for(number)
    return DIGITS[number] if number < 10
    return TEENS[number] if number < 20
    general_case(number)
  end

  def general_case(number)
    hundreds_digit, leftover_digits = number.divmod(100)
    tens_digit, ones_digit = leftover_digits.divmod(10)
    hundreds = DIGITS[hundreds_digit] || nil
    tens = TENS[tens_digit * 10] || nil
    ones = DIGITS[ones_digit] || nil
    format(hundreds, tens, ones)
  end

  def format(hundreds, tens, ones)
    result = ''
    result += "#{hundreds} hundred " if hundreds
    result += tens.to_s if tens
    result += "-#{ones}" if ones
    result.strip
  end
end

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other peopleโ€™s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?