mirror of
https://github.com/jbranchaud/til
synced 2026-01-17 05:58:01 +00:00
Add Zero Padding as a ruby til.
This commit is contained in:
@@ -141,6 +141,7 @@ smart people at [Hashrocket](http://hashrocket.com/).
|
|||||||
- [Summing Collections](ruby/summing-collections.md)
|
- [Summing Collections](ruby/summing-collections.md)
|
||||||
- [Uncaught Exceptions In Pry](ruby/uncaught-exceptions-in-pry.md)
|
- [Uncaught Exceptions In Pry](ruby/uncaught-exceptions-in-pry.md)
|
||||||
- [`undef_method` And The Inheritance Hierarchy](ruby/undef-method-and-the-inheritance-hierarchy.md)
|
- [`undef_method` And The Inheritance Hierarchy](ruby/undef-method-and-the-inheritance-hierarchy.md)
|
||||||
|
- [Zero Padding](ruby/zero-padding.md)
|
||||||
|
|
||||||
### tmux
|
### tmux
|
||||||
|
|
||||||
|
|||||||
22
ruby/zero-padding.md
Normal file
22
ruby/zero-padding.md
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
# Zero Padding
|
||||||
|
|
||||||
|
Ruby makes zero-padding strings to a fixed length easy with `String#rjust`.
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
> "1234".rjust(6, "0")
|
||||||
|
=> "001234"
|
||||||
|
> "123456".rjust(6, "0")
|
||||||
|
=> "123456"
|
||||||
|
```
|
||||||
|
|
||||||
|
In the same way, you can pad zeros on the other side of the string with
|
||||||
|
`String#ljust`.
|
||||||
|
|
||||||
|
```ruby
|
||||||
|
> "12".ljust(4, "0")
|
||||||
|
=> "1200"
|
||||||
|
> "".ljust(4, "0")
|
||||||
|
=> "0000"
|
||||||
|
```
|
||||||
|
|
||||||
|
h/t Dillon Hafer
|
||||||
Reference in New Issue
Block a user