以下是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."
}
Run Code Online (Sandbox Code Playgroud)
我明白这%{}是%Q{}默认情况下,这是字符串插值.但%{}内部双引号的含义是什么?
"%{first} %{second} %{third} %{fourth}"
Run Code Online (Sandbox Code Playgroud)
这条线的意义是什么?
puts formatter % {first: 1, second: 2, third: 3, fourth: 4}
Run Code Online (Sandbox Code Playgroud)
Yu *_*Hao 17
两者都没有关系%Q.
的%之间formatter并且所述散列是String#%方法.
"%{first} %{second} %{third} %{fourth}"是格式字符串,Kernel#sprintf有关详细信息,请参阅.
ehy*_*mel 11
只是为了扩大原来的答案.
sprintf(String#%)的常见用法要求以与格式字符串中的格式代码相同的顺序提供值.格式字符串后面的第一个值用于第一次替换,第二个值用于第二次替换,等等.
sprintf("%d : %f : %d", 123, 456, 789)
=> "123 : 456.000000 : 789"
Run Code Online (Sandbox Code Playgroud)
Ruby还支持格式字符串中的名称引用.要格式化替换值,请使用表单%<name>s.此表单需要格式化代码>.值的顺序(即,在散列中)不确定值的使用位置.相同的值可以使用多次.
sprintf("%<foo>d : %<bar>f : %<bar>d", { :bar => 123, :foo => 456 })
=> "456 : 123.000000 : 123"
Run Code Online (Sandbox Code Playgroud)
如果您不想格式化替换值,则可以使用%{name}不期望格式化代码的表单.后面的任何内容}都被视为文字而不是格式代码.
sprintf("%<foo>s", { :foo => 456 })
=> "456"
sprintf("%{foo} : %{foo}s", { :bar => 123, :foo => 456 })
=> "456 : 456s"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10878 次 |
| 最近记录: |