这是 Zed Shaw 书中的一些代码:
formatter = "%{first} %{second} %{third} %{fourth}"
puts formatter % {first: 1, second: 2, third: 3, fourth: 4}
puts formatter % {first: "one", second: "two", third: "three", fourth: "four"}
puts formatter % {first: true, second: false, third: true, fourth: false}
puts formatter % {first: formatter, second: formatter, third: formatter, fourth: formatter}
puts formatter % {
first: "I had this thing.",
second: "That you could type up right.",
third: "But it didn't sing.",
fourth: "So I said goodnight."
}
我理解%{}
默认是%Q{}
,也就是字符串插值。但是双引号里面的%{}
是什么意思呢?
"%{first} %{second} %{third} %{fourth}"
这行是什么意思?
puts formatter % {first: 1, second: 2, third: 3, fourth: 4}
最佳答案
两者都与 %Q
无关。
formatter
和 hash 之间的 %
是 String#%
方法。
"%{first} %{second} %{third} %{fourth}"
是格式字符串,参见 Kernel#sprintf
了解详情。
关于ruby - 百分比运算符,字符串插值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28556946/