Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do Ruby's printf arguments mean?

Tags:

printf

ruby

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.

like image 620
leonel Avatar asked Dec 15 '22 14:12

leonel


1 Answers

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.

like image 169
Dave Newton Avatar answered Jan 05 '23 05:01

Dave Newton