How to print a number with a thousand separator as spaces in Ruby

1 Answer

0 votes
#
# Program: Print numbers with a thousand separator as spaces in Ruby.
#
# Architecture notes:
# -------------------
# - Ruby does not provide built-in custom thousand separators.
# - We implement a manual formatter:
#     * Convert the number to a string.
#     * Handle negative numbers cleanly.
#     * Insert spaces every three digits from the left.
# - The function is modular, reusable, and efficient.
#
# Performance notes:
# ------------------
# - O(n) time where n is the number of digits.
# - Memory usage is minimal; only small strings are created.
# - No external gems; uses only Ruby's standard library.
#
# Pitfalls:
# ---------
# - Must preserve the minus sign for negative numbers.
# - Must ensure correct grouping even for very large integers.
# - Avoid formatting floats unless converted to integers first.
#
# Security notes:
# ---------------
# - No external input parsing; safe for demonstration.
# - Avoid printing sensitive values in real systems.
#
# Tests:
# ------
# - Positive numbers
# - Negative numbers
# - Zero
# - Very large integers
#


# Format an integer using spaces as thousand separators.
def format_with_spaces(n)
  s = n.to_s

  # Handle negative numbers
  is_negative = s.start_with?('-')
  digits = is_negative ? s[1..] : s

  len_digits = digits.length

  # Determine how many digits before the first space
  first_group = len_digits % 3
  first_group = 3 if first_group == 0

  result = ""
  result << "-" if is_negative

  # First group
  result << digits[0, first_group]

  # Remaining groups
  pos = first_group
  while pos < len_digits
    result << " " << digits[pos, 3]
    pos += 3
  end

  result
end


def main
  tests = [
    0,
    42,
    1234,
    987_654_321,
    -1_234_567,
    1_000_000_000_000_000_000 # 10^18
  ]

  puts "Running test cases:\n\n"

  tests.each do |n|
    puts "Original:  #{n}"
    puts "Formatted: #{format_with_spaces(n)}"
    puts
  end
end


main


# run:
#
# Running test cases:
#
# Running test cases:
# 
# Original:  0
# Formatted: 0
# 
# Original:  42
# Formatted: 42
# 
# Original:  1234
# Formatted: 1 234
# 
# Original:  987654321
# Formatted: 987 654 321
# 
# Original:  -1234567
# Formatted: -1 234 567
# 
# Original:  1000000000000000000
# Formatted: 1 000 000 000 000 000 000
# 

 



answered Sep 22 by avibootz
...