module Format
Definitions
def count(value, units = UNITS, scale: 1000)
Format a count into a human-readable string.
Signature
-
parameter
value
Numeric
The count to format.
-
parameter
units
Array
The units to use for formatting (default: UNITS).
-
parameter
scale
Numeric
The scaling factor between units (default: 1000).
-
returns
String
A formatted string representing the count.
Implementation
def count(value, units = UNITS, scale: 1000)
value = value
index = 0
limit = units.size - 1
# Handle negative numbers by working with absolute value:
negative = value < 0
value = value.abs
while value >= scale and index < limit
value = value / scale.to_f
index += 1
end
result = String.new
result << "-" if negative
result << value.round(2).to_s
result << units[index].to_s if units[index]
return result
end
def decimal(value, precision: 2)
Format a numeric value as a decimal with specified precision.
Signature
-
parameter
value
Numeric
The numeric value to format.
-
parameter
precision
Integer
Number of decimal places (default: 2).
-
returns
String
A formatted decimal string.
Implementation
def decimal(value, precision: 2)
value.round(precision).to_s
end
def ratio(current, total)
Format a ratio as "current/total" with human-readable counts.
Signature
-
parameter
current
Numeric
The current value.
-
parameter
total
Numeric
The total value.
-
returns
String
A formatted ratio string.
Implementation
def ratio(current, total)
"#{count(current)}/#{count(total)}"
end
def snake_case(string)
Convert a string to snake_case
.
Signature
-
parameter
string
String
The string to convert.
-
returns
String
A snake_cased string.
Implementation
def snake_case(string)
string = string.gsub("::", "")
string.gsub!(/(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/, "_")
string.downcase!
string.sub!(/^_+/, "")
return string
end
def statistics(pairs, short: true)
Format multiple statistics into a compact string.
Signature
-
parameter
pairs
Hash
Hash of statistic names to values or [current, total] arrays.
-
parameter
short
Boolean
Whether to use short keys (first letter only).
-
returns
String
A formatted statistics string.
Implementation
def statistics(pairs, short: true)
pairs.map do |key, value|
case value
when Array
value = value.map(&method(:count)).join("/")
when Numeric
value = count(value)
end
if short
key = key.to_s[0].upcase
else
key = key.to_s.upcase
end
"#{key}=#{value}"
end.join(" ")
end
def title_case(string)
Convert a string to title case.
Signature
-
parameter
string
String
The string to convert.
-
returns
String
A title-cased string.
Implementation
def title_case(string)
string = string.gsub(/(^|[ \-_])(.)/){" " + $2.upcase}
string.strip!
return string
end