Dave Burt
12/22/2005 1:35:00 AM
> irb(main):004:0> sprintf("%2s", "lalaa")
> => "lalaa"
> irb(main):005:0> sprintf("%2i", 1212)
> => "1212"
>
> What s my mistake?
Daniel Sheppard wrote:
> sprintf("%2.2s","lalaa")
> ==>"la"
>
> u can't do the equivalent for a number (as the precision setting for a
> number specifies decimal places).
You _can_ do the equivalent for a number two ways that I can think of:
sprintf("%i", 1212 % 10**2) #=> "12" # modular arithmetic to truncate high
digits
sprintf("%.2s", 1212) #=> "12" # cast integer to string
Also, I usually like using String#% instead of sprintf, just in case you're
not familiar with it:
"%.2s" % 1212 #=> "12"
Cheers,
Dave