Forum: Ruby Re: sprintf

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Daniel S. (Guest)
on 2005-12-22 02:42
(Received via mailing list)
> 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
#####################################################################################
Dave B. (Guest)
on 2005-12-22 03:39
(Received via mailing list)
> irb(main):004:0> sprintf("%2s", "lalaa")
> => "lalaa"
> irb(main):005:0> sprintf("%2i", 1212)
> => "1212"
>
> What s my mistake?

Daniel S. 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 (Guest)
on 2005-12-22 03:45
(Received via mailing list)
* Dave B. (removed_email_address@domain.invalid) 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://ackro.org

ruby -e "0.upto((a='njduspAhnbjm/dpn').size-1){|x| a[x]-=1}; p
'mailto:'+a"
This topic is locked and can not be replied to.