4

Can someone please help me understand the following expression?

printf("%3d - %s\n", counter, name)

That line prints something like this 6 - Install Adobe software

I have looked up information and read the reference but I can't find a simple answer and I'm a bit confused. If you can refer me to a good reference, please do so.

%3d Ok, according to what I could understand, %3d is the number of characters or spaces. Please point me to a reference that explains it.

%s\n I couldn't figure out what this does. I guess \n is a newline or something similar, but by looking at the output it doesn't seem to work like that.

Why are counter and name variables separated by commas?

By looking at the output is seems that %3d is kind of replaced by counter and %s\n is replaced by name. I'm not sure how it works but I would like to understand it.

2
  • nope, come from a html/css php background. doing RoR for a while now too, and trying to learn Ruby more in depth.
    – leonel
    Jan 24, 2013 at 17:47
  • 18
    @texasbruce as you can see not everyone comes from C. It's never stated as a precondition to learn Ruby. There is no "C" tag on the question. hence you comments are irrelevant.
    – inger
    Feb 24, 2014 at 18:12

1 Answer 1

12

For syntax look at any printf docs, but check the sprintf docs on ruby-doc.

They're separated by commas because they're separate parameters to the function, but that's more or less syntactic sugar. Think varargs.

Not sure what you mean with the %s\n thing, it's a string then a newline: that's what it outputs.

If your question is specifically "how does the code turn a formatting string and a group of arguments into output" I'd probably search for source, for example, a tiny embedded printf. Nutshell version is that the format string is searched for formatting options, they consume their associated parameters, outputting an appropriately-formatted string. It's a tiny little DSL.

1
  • 1
    +1 And the ruby-doc.org version has the examples formatted correctly - you might want to link there instead. Jan 24, 2013 at 16:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.