简体   繁体   English

Ruby的printf参数是什么意思?

[英]What do Ruby's printf arguments mean?

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. 如果您可以参考我的好参考,请这样做。

%3d Ok, according to what I could understand, %3d is the number of characters or spaces. %3d好的,根据我的理解, %3d是字符或空格的数量。 Please point me to a reference that explains it. 请指出一个解释它的参考。

%s\\n I couldn't figure out what this does. %s\\n我无法弄清楚这是做什么的。 I guess \\n is a newline or something similar, but by looking at the output it doesn't seem to work like that. 我猜\\n是换行符或类似的东西,但通过查看输出它似乎不像那样工作。

Why are counter and name variables separated by commas? 为什么用逗号分隔countername变量?

By looking at the output is seems that %3d is kind of replaced by counter and %s\\n is replaced by name . 通过查看输出似乎%3dcounter替换, %s\\nname替换。 I'm not sure how it works but I would like to understand it. 我不确定它是如何工作的,但我想了解它。

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. 想想varargs。

Not sure what you mean with the %s\\n thing, 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 . 如果您的问题具体是“代码如何将格式化字符串和一组参数转换为输出”我可能会搜索源代码,例如,一个微小的嵌入式printf Nutshell version is that the format string is searched for formatting options, they consume their associated parameters, outputting an appropriately-formatted string. Nutshell版本是搜索格式字符串的格式化选项,它们使用相关参数,输出格式正确的字符串。 It's a tiny little DSL. 这是一个小小的DSL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM