2 Replies - 990 Views - Last Post: 27 February 2014 - 08:44 AM Rate Topic: -----

#1 heaphyg  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 85
  • Joined: 30-August 13

3d?

Posted 26 February 2014 - 09:33 PM

The following code prints out a times table. I am not sure what the 3d part is all about but I do notice that when I change the value in front of the d the spacing of the numbers changes in the output. If i get rid of the -3d all together the code doesn't work. I believe that the the % symbol is just a place holder for (i *j) if I'm not mistaken.

x = (1..5)
y = (1..5)
 
y.each do |j| # 1,2,3,4,5
    x.each {|i| print "%-3d  " % (i*j)}
    print "\n"
end



Is This A Good Question/Topic? 0
  • +

Replies To: 3d?

#2 heaphyg  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 85
  • Joined: 30-August 13

Re: 3d?

Posted 26 February 2014 - 11:10 PM

I see that the %d is reference specifically for digits (seemingly a kind of string interpolation) but I'm still a bit confused about the 3 in front of the d which seems to deal with the formatting of the string. In addition I notice that omitting the dash (%3d as opposed to %-3d) alters the formatting as well independent of the number 3. As far as I can tell including the dash produces output that is flush against the left edge of the console. The number (3 in this case) perhaps determines the number of white spaces between printed strings. Any additional refinement to this explanation would be greatly appreciated.

This post has been edited by heaphyg: 26 February 2014 - 11:20 PM

Was This Post Helpful? 0
  • +
  • -

#3 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2118
  • View blog
  • Posts: 3,244
  • Joined: 21-June 11

Re: 3d?

Posted 27 February 2014 - 08:44 AM

d stands for "decimal", not digit, indicating that the number will be printed in base 10 - as opposed to %o and %x, which would print the number in base 8 (Octal) and base 16 (heXadecimal) respectively. The number you're printing does not have to consist of only one digit.

Other than that you're right: the number before the d determines how wide the number is supposed to be displayed (i.e. how much padding to add if necessary - it does not truncate though) and the - determines the alignment.

See the documentation of % and sprintf for more information.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1