我的应用程序中有字段hrmin,它们都是整数。对于hr字段,如果用户输入“1”,我希望Rails在将其保存到数据库之前将其自动填充为“01”。同样对于min字段,如果用户输入“0”,则应将其输入为“00”。

我怎样才能做到这一点?

最佳答案

最好将其存储为整数,然后按照运行时中的描述进行显示。每种语言都有自己的补零方式-对于Ruby,您可以使用String#rjust。此方法使用给定的填充字符填充字符串(右对齐),使其变为给定的长度。


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'

关于ruby - 导轨中的前导零,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5810468/

10-11 15:36