Ruby 的 printf 参数是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14505621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What do Ruby's printf arguments mean?
提问by leonel
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
那条线打印出这样的东西 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.
我查了资料并阅读了参考资料,但找不到简单的答案,我有点困惑。如果你能给我推荐一个好的参考资料,请这样做。
%3dOk, according to what I could understand, %3dis the number of characters or spaces. Please point me to a reference that explains it.
%3d好的,根据我的理解,%3d是字符数或空格数。请向我指出解释它的参考资料。
%s\nI couldn't figure out what this does. I guess \nis a newline or something similar, but by looking at the output it doesn't seem to work like that.
%s\n我无法弄清楚这是做什么的。我想\n是换行符或类似的东西,但通过查看输出,它似乎并没有那样工作。
Why are counterand namevariables separated by commas?
为什么counter和name变量用逗号分隔?
By looking at the output is seems that %3dis kind of replaced by counterand %s\nis replaced by name. I'm not sure how it works but I would like to understand it.
通过查看输出似乎%3d是种替换counter和%s\n被替换name。我不确定它是如何工作的,但我想了解它。
回答by Dave Newton
For syntax look at any printf docs, but check the sprintf docs on ruby-doc.
有关语法,请查看任何 printf 文档,但请查看ruby-doc 上的sprintf 文档。
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\nthing, it's a string then a newline: that's what it outputs.
不确定你的意思是%s\n什么,它是一个字符串,然后是一个换行符:这就是它输出的内容。
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.
如果您的问题特别是“代码如何将格式化字符串和一组参数转换为输出”,我可能会搜索源代码,例如一个很小的嵌入式 printf。简而言之,在格式字符串中搜索格式选项,它们使用相关参数,输出格式正确的字符串。这是一个很小的DSL。

