💎Ruby tip: Powerful string formatter

Sebastien Auriault
Jun 24, 2022
Did you know that Ruby gives you a powerful string formatter to do things like choosing the number of decimals, converting to binary, octal, hexadecimal, and a lot more?

Examples ⬇️
# Make a number always show 2 decimals (useful for money)
"%.2f" % 10 # => "10.00"
"%.2f" % 10.50 # => "10.50"

# You can even add the currency sign
"$%.2f" % 10.50 # => "$10.50"

# Convert to hexadecimal
"%#x" % 1234 # => "0x4d2"

# And it can do a lot more!

# % is a shortcut that uses Kernel#sprintf behind the scenes
# so if you're looking for the format specification, check
# out the doc of sprintf
sprintf("%#x", 1234) # => "0x4d2"