What is the proper way to ensure a string length in Ruby? The string is multi-byte (UTF8). The strings inputted can be either too short, exactly right, or too long. It would need respectively padding, nothing and slicing.
I can get there in two steps:
def ensure_length(str, length)
str.ljust(length).slice(0, length)
end
Is there a single method for this? And if it needs in two steps, what order is best: ljust then slice or vice versa, and why?
p "%-10.10s" % "abcdabcdabcd"
In which the first -10 pads the string to 10 like ljust
and the second 10 is the max number of characters. Documented under sprintf.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments