Ruby 的 printf 参数是什么意思? [英] What do Ruby's printf arguments mean?
问题描述
有人能帮我理解下面的表达吗?
Can someone please help me understand the following expression?
printf("%3d - %s\n", counter, name)
该行打印出类似这样的内容 6 - 安装 Adobe 软件
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
好吧,据我了解,%3d
是字符数或空格数.请向我指出解释它的参考资料.
%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
我不知道这是做什么的.我猜 \n
是换行符或类似的东西,但通过查看输出,它似乎并没有像那样工作.
%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.
为什么counter
和name
变量用逗号分隔?
Why are counter
and name
variables separated by commas?
通过查看输出,似乎 %3d
被 counter
替换,%s\n
被 替换>名称代码>.我不确定它是如何工作的,但我想了解它.
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.
推荐答案
有关语法,请查看任何 printf 文档,但请查看 关于 ruby-doc 的 sprintf 文档.
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.
不确定你对 %s\n
的意思,它是一个字符串,然后是一个换行符:这就是它输出的内容.
Not sure what you mean with the %s\n
thing, it's a string then a newline: that's what it outputs.
如果您的问题特别是代码如何将格式化字符串和一组参数转换为输出",我可能会搜索源代码,例如,微型嵌入式 printf.简而言之,在格式字符串中搜索格式化选项,它们使用相关参数,输出格式正确的字符串.这是一个很小的 DSL.
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.
这篇关于Ruby 的 printf 参数是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!