Leading zeros in Ruby

It’d be better to store it as an integer and just display it as you described on runtime. Every language has its own way to pad zeros – for Ruby you can use String#rjust. This method pads a string (right-justified) so that it becomes a given length, using a given padding character.

str.rjust(integer, padstr=" ") → new_str

If integer is greater than the length of str, returns a new String of length integer with str right justified and padded with padstr; otherwise, returns str.

some_int = 5
some_int.to_s.rjust(2, '0')  # => '05'
some_int.to_s.rjust(5, '0')  # => '00005'

another_int = 150
another_int.to_s.rjust(2, '0') # => '150'
another_int.to_s.rjust(3, '0') # => '150'
another_int.to_s.rjust(5, '0') # => '00150'

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)