Flowdock

Notes posted by diwadm

RSS feed
March 12, 2009 - (v1_8_6_287 - v1_8_7_72)
1 thank

Autopad Numbers with Zeros (0s)

Here’s a handy code for padding 0s in a string. This is useful when you need to generate numbers for forms, such as invoices or orders. For example, you want to turn an invoice number 12345 to 0012345:

$ irb

>> s = "0000000"
=> "0000000"

>> num = "12345"
=> "12345"

>> s.insert(-(num.to_s.length + 1), num.to_s)[0, s.length - num.to_s.length] if num.to_s.length <= s.length
=> "0012345"