[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: sprintf

Daniel Sheppard

12/22/2005 12:40:00 AM


> irb(main):004:0> sprintf("%2s", "lalaa")
> => "lalaa"
> irb(main):005:0> sprintf("%2i", 1212)
> => "1212"
>
> ruby 1.8.3 (2005-09-21) [i686-linux]
>
> What s my mistake?

Reading comprehension? =)

sprintf("%2.2s","lalaa")
==>"la"

You can't do the equivalent for a number (as the precision setting for a
number specifies decimal places).
#####################################################################################
This email has been scanned by MailMarshal, an email content filter.
#####################################################################################
#####################################################################################
This e-mail message has been scanned for Viruses and Content and cleared
by NetIQ MailMarshal
#####################################################################################


2 Answers

Dave Burt

12/22/2005 1:35:00 AM

0

> 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


Michael 'entropie' Trommer

12/22/2005 1:43:00 AM

0

* Dave Burt (dave@burt.id.au) wrote:
> Also, I usually like using String#% instead of sprintf, just in case you're
> not familiar with it:
>
> "%.2s" % 1212 #=> "12"
>

i wasnt familiar with it, quite impressive!

So long
--
Michael 'entropie' Trommer; http:/...

ruby -e "0.upto((a='njduspAhnbjm/dpn').size-1){|x| a[x]-=1}; p 'mailto:'+a"