Skip to content

Instantly share code, notes, and snippets.

@veelenga
Last active March 24, 2016 21:10
Show Gist options
  • Save veelenga/21e42a629ae1b39222d3 to your computer and use it in GitHub Desktop.
Save veelenga/21e42a629ae1b39222d3 to your computer and use it in GitHub Desktop.
left-pad for Crystal
class String
def leftpad(len : Int, char = ' ')
char, len = char.to_s, len - self.size
raise ArgumentError.new if char.size != 1
len > 0 ? (char * len + self) : self
end
end
p "foo".leftpad(5) # => " foo"
p "foobar".leftpad(8) # => " foobar"
p "foobar".leftpad(6) # => "foobar"
p "1".leftpad(10, 0) # => "0000000001"
@jgaskins
Copy link

There's String#rjust and String#ljust built in, as well. No need to monkeypatch. :-)

p "foo".rjust(5)      # => "  foo"
p "footer".rjust(8)   # => "  foobar"
p "footer".rjust(6)   # => "foobar"
p "1".rjust(10, '0')  # => "0000000001"

@veelenga
Copy link
Author

@jgaskins yeah, but with built-in stuff there is no way to repeat npm fiasco... :-)

@jgaskins
Copy link

@veelenga HA!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment